Canvas change lineWidth on drawing after it has been drawn

微笑、不失礼 提交于 2020-01-17 06:03:56

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!