You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Canvas中绘制红圈轨迹并实现点击后沿蓝圈方向移动

实现方案

核心改动说明

  • 新增redTrail数组存储红色圆形每帧的坐标,用于绘制移动轨迹
  • 新增方向向量变量dx、dy和速度变量moveSpeed控制红色圆形移动,默认水平向右
  • 将点击事件绑定移出动画循环,避免重复绑定导致性能问题,点击时根据当前蓝色圆形相对红色圆形的位置计算新的移动方向
  • 调整绘制顺序:每一帧先清空画布,再绘制红色圆形轨迹,再绘制两个圆形

完整修改后代码

JavaScript代码

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

// 蓝色圆形相对红色圆形的偏移坐标
let offsetX = 100;
let offsetY = 100;
// 红色圆形坐标
let redX = 50;
let redY = 50;
let angle = 0;
// 红色圆形轨迹存储
const redTrail = [];
// 红色圆形移动速度、方向向量
const moveSpeed = 1;
let dx = moveSpeed;
let dy = 0;

// 绘制红色圆形
function drawRedCircle(){
    ctx.fillStyle = 'red';
    ctx.beginPath();
    ctx.arc(redX, redY, 20, 0, Math.PI * 2);
    ctx.closePath();
    ctx.fill();
}

// 绘制蓝色圆形
function drawBlueCircle(){
    ctx.fillStyle = 'blue';
    ctx.beginPath();
    ctx.arc(redX + offsetX, redY + offsetY, 10, 0, Math.PI * 2);
    ctx.closePath();
    ctx.fill();
}

// 绘制红色圆形轨迹
function drawRedTrail() {
    ctx.fillStyle = 'rgba(255, 0, 0, 0.5)';
    redTrail.forEach(point => {
        ctx.beginPath();
        ctx.arc(point.x, point.y, 2, 0, Math.PI * 2);
        ctx.closePath();
        ctx.fill();
    })
}

// 点击事件绑定
canvas.addEventListener('click', () => {
    // 计算蓝色圆形相对红色圆形的方向向量
    const directionX = offsetX;
    const directionY = offsetY;
    // 归一化向量,保证移动速度不变
    const length = Math.sqrt(directionX * directionX + directionY * directionY);
    dx = (directionX / length) * moveSpeed;
    dy = (directionY / length) * moveSpeed;
})

function animate(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 存储当前红色圆形坐标到轨迹数组
    redTrail.push({x: redX, y: redY});
    // 绘制轨迹
    drawRedTrail();
    // 绘制两个圆形
    drawRedCircle();
    drawBlueCircle();

    // 更新蓝色圆形的旋转偏移
    offsetX = 35 * Math.sin(angle);
    offsetY = 35 * Math.cos(angle);
    // 更新红色圆形位置
    redX += dx;
    redY += dy;

    angle += 0.1;
    requestAnimationFrame(animate);
}

animate();

CSS代码(无修改)

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

HTML代码(无修改)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas basics</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <canvas id="canvas1"></canvas>
    
    <script src="script.js"></script>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 14:36:02