所以我想使用 requestAnimationFrame 在 HTML 5 Canvas 上绘制线条动画。
我已经做到了
function animateWrapper(centerX, centerY, xAngle, yAngle, width, height) {
var request = requestAnimationFrame(animate);
var canvas = document.getElementById("drawing");
var context = canvas.getContext('2d');
function animate (centerX, centerY, xAngle, width, height) {
drawLine(centerX,centerY, centerX, centerY - height, context, request);
}
}
function drawLine(startX, startY, endX, endY, context, request) {
context.beginPath();
context.moveTo(startX, startY);
step += 0.05;
// if (step > 1) step = 1;
var newX = startX + (endX - startX) * step;
var newY = startY + (endY - startY) * step;
context.lineTo(newX, newY);
context.stroke();
if (Math.abs(newX) >= Math.abs(endX) && Math.abs(newY) >= Math.abs(endY)) {
cancelAnimationFrame(request);
step = 0;
}
}
$(document).ready(function(){
animateWrapper(100, 100, 40, 40, 400, 400);
});
现在 centerY、xAngle、宽度、高度都未定义(这是有道理的 - 它们没有被传入)。这会导致 endY 变为 NaN,因此动画不会发生。
我不知道如何解决这个问题 - 如何在请求动画帧中传递这些参数?
最佳答案
这应该有效:
function animateWrapper(centerX, centerY, xAngle, yAngle, width, height) {
function animate () {
drawLine(centerX,centerY, centerX, centerY - height, context, request);
}
var request = requestAnimationFrame(animate);
var canvas = document.getElementById("drawing");
var context = canvas.getContext('2d');
}
您不必使用任何参数调用 animate()
,因为变量 centerX
、centerY
、... 和 height
在定义 animate()
时就在范围内(即它们当时是已知的,因此您可以简单地在函数内部使用它们)。
这个问题的答案列出了变量在 JavaScript 中可见/可用的各种方式:What is the scope of variables in JavaScript?
关于javascript - 在 Canvas 上逐步绘制线条动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23602952/