js canvas 自定义飞行轨迹 ,线性流动

<!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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值