【发布时间】:2021-10-30 09:15:18
【问题描述】:
我想创建一个动画,其中的图像画布遵循一个半圆形。起初我尝试使用画布arc,但我发现使用bezier curve 更简单。
但现在我遇到了一个问题,因为它不在一个圆圈上,我无法找到一种方法让它根据它的位置旋转,就像手表指针一样。这是我目前的代码。
var c = document.getElementById('myCanvas');
var ctx = c.getContext('2d');
var statue = new Image();
statue.src = 'https://i.ibb.co/3TvCH8n/liberty.png';
function getQuadraticBezierXYatPercent(startPt, controlPt, endPt, percent) {
var x =
Math.pow(1 - percent, 2) * startPt.x +
2 * (1 - percent) * percent * controlPt.x +
Math.pow(percent, 2) * endPt.x;
var y =
Math.pow(1 - percent, 2) * startPt.y +
2 * (1 - percent) * percent * controlPt.y +
Math.pow(percent, 2) * endPt.y;
return { x: x, y: y };
}
const startPt = { x: 600, y: 200 };
const controlPt = { x: 300, y: 100 };
const endPt = { x: 0, y: 200 };
var percent = 0;
statue.addEventListener('load', () => {
animate();
});
function animate() {
//console.log(percent);
ctx.clearRect(0, 0, c.width, c.height);
percent > 1 ? (percent = 0) : (percent += 0.003);
var point = getQuadraticBezierXYatPercent(startPt, controlPt, endPt, percent);
ctx.drawImage(
statue,
0,
0,
statue.width,
statue.height,
point.x - 50,
point.y - 50,
100,
100
);
//ctx.fillRect(point.x, point.y, 10, 10);
requestAnimationFrame(animate);
}
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="600" height="200" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
</script>
</body>
</html>
这样做的正确方法是什么?
【问题讨论】:
-
你能解释一下为什么贝塞尔曲线更容易,因为作为一个对贝塞尔曲线有点了解的人:圆弧比贝塞尔曲线远容易。
-
这是因为我可以通过一个不涉及三角函数的简单函数获得我想要的形状(一个稍微变平的半圆)和特定时间的图像位置。
-
以非线性路径运动和微积分而不是三角函数为代价,这是一个任意差异(二次计算更复杂并且比弧数学更昂贵)
标签: html animation canvas bezier