我在画布上渲染了一条二次曲线。我想通过 window.setInterval 对其进行动画处理,然后更改它的尺寸(注意不是简单地改变它的比例)。
如何在调用 context.closePath() 后保留对路径的可编辑引用?
我在画布上渲染了一条二次曲线。我想通过 window.setInterval 对其进行动画处理,然后更改它的尺寸(注意不是简单地改变它的比例)。
如何在调用 context.closePath() 后保留对路径的可编辑引用?
我建议您在新Path
对象中维护对路径的引用;这样您就可以动态修改 x、y、点等,然后在每个动画步骤中渲染它。
var testPath = new Path(100, 100, [[40, 40], [80, 80]]);
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
function Path(x, y, points)
{
this.x = x;
this.y = y;
this.points = points;
}
function update()
{
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = 'red';
ctx.moveTo(testPath.points[0][0], testPath.points[0][1]);
for (var i = 1; i < testPath.points.length; i++)
{
ctx.lineTo(testPath.points[i][0], testPath.points[i][1]);
}
ctx.stroke();
testPath.points[1][1]++; // move down
// loop
requestAnimationFrame(update);
}
update();
出于某种原因,JSFiddle 与 Paul Irish 的 requestAnimationFrame polyfill 不兼容,但它应该在本地工作。我肯定会推荐这个而不是 setInterval。