本文介绍了如何用Canvas绘制一个曲线的动画?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一堆点,我想慢慢画。我尝试setTimeOut和此的效果。但是没有这么多成功。
i have a bunch of points that i wanted to slowly draw. I try setTimeOut and the effect from this tutorial. But without so much success.
函数看起来像这样
var myFunction = function(ctx, grid, points) {
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
ctx.lineWidth = 2;
ctx.strokeStyle = '#2068A8';
ctx.fillStyle = '#2068A8';
var count = 1;
for (count = 1; count < points.length; count++) {
ctx.lineTo(points[count].x , points[count].y);
}
ctx.stroke();
}
在这个函数周围有很多其他绘图函数,但我只想动画
Around this function there a many other drawing functions but i just want to animate only one.
推荐答案
p>有两种方法可以做到这一点,我可以想到从我的头顶。一个是绘制一个点,并在绘制另一个点之前暂停一定时间。这是我提供的第一个例子。第二种方法涉及绘制局部线到当前目标,这使得更平滑的绘图外观。作为旁注,我使用
Live Demo
如果您发现有点波动,您可以执行以下操作,以获得更平滑的线条
If you notice that is a bit choppy, you can do the following to get smoother lines being drawn
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
canvas.width = 400;
canvas.height = 200;
var points = [],
currentPoint = 1,
speed = 2,
targetX = 0,
targetY = 0,
x = 0,
y = 0;
// make some points
for (var i = 0; i < 50; i++) {
points.push({
x: i * (canvas.width/50),
y: 100+Math.sin(i) * 10
});
}
// set the initial target and starting point
targetX = points[1].x;
targetY = points[1].y;
x = points[0].x;
y = points[0].y;
function draw() {
var tx = targetX - x,
ty = targetY - y,
dist = Math.sqrt(tx*tx+ty*ty),
velX = (tx/dist)*speed,
velY = (ty/dist)*speed;
x += velX
y += velY;
if(dist < 1){
currentPoint++;
if(currentPoint >= points.length){
currentPoint = 1;
x = points[0].x;
y = points[0].y;
}
targetX = points[currentPoint].x;
targetY = points[currentPoint].y;
}
ctx.clearRect(0,0,canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
ctx.lineWidth = 2;
ctx.strokeStyle = '#2068A8';
ctx.fillStyle = '#2068A8';
for (var p = 0, plen = currentPoint-1; p < plen; p++) {
ctx.lineTo(points[p].x, points[p].y);
}
ctx.lineTo(x, y);
ctx.stroke();
requestAnimFrame(draw);
}
draw();
Live Demo
这篇关于如何用Canvas绘制一个曲线的动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!