画布在绘制后在其上更改lineWidth
问题描述:
在画布中,可以更改图形的线宽吗?
In canvas, is it possible to change the lineWidth of a drawing?
示例:
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>
它已经绘制了,但是我想在绘制之后更改lineWidth.
It has already been drawn, but I want to change the lineWidth after it is drawn.
答
如果您要重新绘制具有新线宽的线,则很有可能.您可以使用 requestAnimationFrame
.这是一个小目的,目的是向您展示我的意思.
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>