我有一堆要点想慢慢画。我尝试 setTimeOut 和这个 tutorial 的效果.但没有那么成功。
函数看起来像这样
函数:
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();
}
围绕这个函数还有很多其他的绘图函数,但我只想制作一个动画。
如何用canvas慢慢画一个函数?
最佳答案
我想到了两种方法来完成此操作。一个基本上是绘制一个点并在绘制另一个点之前暂停一定时间。这是我提供的第一个示例。第二种方法涉及绘制部分线到当前目标,这提供了更平滑的绘图外观。作为旁注,我使用 requestAnimationFrame
在这两个示例中,它都是执行任何类型的 Canvas 动画的推荐方法。
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
canvas.width = 400;
canvas.height = 200;
var points = [],
currentPoint = 1,
nextTime = new Date().getTime()+500,
pace = 200;
// make some points
for (var i = 0; i < 50; i++) {
points.push({
x: i * (canvas.width/50),
y: 100+Math.sin(i) * 10
});
}
function draw() {
if(new Date().getTime() > nextTime){
nextTime = new Date().getTime() + pace;
currentPoint++;
if(currentPoint > points.length){
currentPoint = 0;
}
}
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 = 1, plen = currentPoint; p < plen; p++) {
ctx.lineTo(points[p].x, points[p].y);
}
ctx.stroke();
requestAnimFrame(draw);
}
draw();
如果您注意到它有点不连贯,您可以执行以下操作以使绘制的线条更平滑
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();
关于javascript - 如何使用 Canvas 动画绘制曲线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14484678/