<!DOCTYPE html>
<html>
<head>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="300" height="200"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 三个点的坐标
const points = [
{ x: 25, y: 121 },
{ x: 135, y: 34 },
{ x: 259, y: 141 }
];
let t = 0;
const animationSpeed = 0.005;
// let isAnimating = true;
// const animationDuration = 3000; // 每次动画的持续时间(毫秒)
function drawCurve() {
// if (!isAnimating) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制控制点
ctx.fillStyle = 'blue';
for (const point of points) {
ctx.beginPath();
ctx.arc(point.x, point.y, 5, 0, Math.PI * 2);
ctx.fill();
}
// 计算贝塞尔曲线上的坐标
const x = (1 - t) * (1 - t) * points[0].x + 2 * (1 - t) * t * points[1].x + t * t * points[2].x;
const y = (1 - t) * (1 - t) * points[0].y + 2 * (1 - t) * t * points[1].y + t * t * points[2].y;
// 绘制移动的点
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(x, y, 8, 0, Math.PI * 2);
ctx.fill();
// 绘制贝塞尔曲线
ctx.strokeStyle = 'black';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
ctx.quadraticCurveTo(points[1].x, points[1].y, points[2].x, points[2].y);
ctx.stroke();
t += animationSpeed;
if (t > 1) {
t = 0;
// isAnimating = false; // 暂停动画
// setTimeout(() => {
// isAnimating = true; // 重新开始动画
// requestAnimationFrame(drawCurve);
// }, animationDuration);
}
requestAnimationFrame(drawCurve);
}
// 点击获取坐标
canvas.addEventListener('click', (event) => {
const rect = canvas.getBoundingClientRect();
const mouseX = event.clientX - rect.left;
const mouseY = event.clientY - rect.top;
console.log('点击坐标:', mouseX, mouseY);
});
drawCurve();
</script>
</body>
</html>
js canvas 自定义飞行轨迹 ,线性流动
最新推荐文章于 2024-08-14 03:10:22 发布