问题
In canvas, is it possible to change the lineWidth of a drawing?
Example:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineWidth = 15;
ctx.lineTo(100, 100);
ctx.stroke();
<canvas id="canvas"></canvas>
It has already been drawn, but I want to change the lineWidth after it is drawn.
回答1:
If you're asking about redrawing the line with a new line width, that's quite possible. You can use requestAnimationFrame
. Here's a little aimation to show you what I mean.
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
requestAnimationFrame(draw);
function draw(timestamp) {
var period = 0.5;
var t = Date.now()%(period*1000)/(period*1000);
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineWidth = 15+5*Math.sin(t*2*Math.PI);
ctx.lineTo(100, 100);
ctx.stroke();
requestAnimationFrame(draw);
}
<canvas id="canvas"></canvas>
回答2:
I'm afraid you'll need to re-draw it with a different line width.
The reason is that path
cannot be stored as a variable, so you cannot call ctx.stroke()
on the same path multiple times. Animation frames are probably your best bet.
来源:https://stackoverflow.com/questions/38691276/canvas-change-linewidth-on-drawing-after-it-has-been-drawn