You need to enable JavaScript to run this app. 鼠标按下时如何让Canvas上的对象沿指定方向持续移动
优惠活动
大模型
产品
解决方案
定价
更多

鼠标按下时如何让Canvas上的对象沿指定方向持续移动

Canvas 圆形跟随移动功能实现

核心修改点

  • 新增isMouseDown状态变量,监听鼠标按下/抬起/移出事件更新状态,识别鼠标长按场景
  • 把红色圆形的移动逻辑移入逐帧执行的animate函数中,实现长按期间持续移动
  • 蓝色圆形的环绕旋转逻辑新增状态判断,鼠标按下时停止角度更新,固定在当前方向作为前进指引
  • 新增移动速度归一化处理,保证不同方向移动速度均匀可控

完整可运行代码

HTML 代码

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <canvas id="canvas1"></canvas>
    <script src="script.js"></script>
</body>
</html>

CSS 代码

#canvas1{
    position: absolute;
    top:0;
    left: 0;
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}

JavaScript 代码

const canvas = document.getElementById('canvas1');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

// 原有基础变量
let positionX = 100;
let positionY = 100;
let X = 50;
let Y = 50;
let angle = 0;

// 新增控制变量
let isMouseDown = false;
const moveSpeed = 3; // 可自行调整移动速度

// 鼠标事件监听
canvas.addEventListener('mousedown', () => isMouseDown = true);
canvas.addEventListener('mouseup', () => isMouseDown = false);
canvas.addEventListener('mouseout', () => isMouseDown = false); // 鼠标移出画布自动停止

function circle(){
    ctx.fillStyle = 'red';
    ctx.beginPath();
    ctx.arc(X, Y, 20, 0, Math.PI*2);
    ctx.closePath();
    ctx.fill();
}

function direction(){
    ctx.fillStyle = 'blue';
    ctx.beginPath();
    ctx.arc(positionX + X, positionY + Y, 10, 0, Math.PI*2);
    ctx.closePath();
    // 鼠标按下时停止旋转,保持方向
    if (!isMouseDown) {
        positionX = 35 * Math.sin(angle);
        positionY = 35 * Math.cos(angle);
        angle += 0.1;
    }
    ctx.fill();   
}

function animate(){
    ctx.clearRect(0,0, canvas.width, canvas.height);
    // 鼠标按下时持续移动
    if (isMouseDown) {
        // 归一化方向向量,保证移动速度均匀
        X += positionX * moveSpeed / 35;
        Y += positionY * moveSpeed / 35;
    }
    circle();
    direction();
    requestAnimationFrame(animate);   
}
animate();

内容的提问来源于stack exchange,提问作者mahesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 15:24:02