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

点击按钮克隆Canvas矩形并实现左移动画:克隆Canvas问题求助

解决Canvas点击生成左移矩形的问题

嘿,我看你遇到了Canvas生成左移矩形的问题,其实根本不需要克隆Canvas啦!咱们换个思路,用对象来管理每个矩形的状态,在同一个Canvas上绘制它们的移动过程就好,我给你整理了完整的解决方案:

1. HTML结构准备

首先咱们需要一个触发按钮和一个Canvas容器:

<button id="addRect">点击生成矩形</button>
<canvas id="myCanvas" width="800" height="200" style="border: 1px solid #333;"></canvas>

2. JavaScript实现逻辑

咱们用数组来存储所有矩形的状态,每次点击按钮就添加一个新的矩形实例,然后通过requestAnimationFrame实现流畅的动画循环:

$(document).ready(function(){
    // 兼容各浏览器的requestAnimationFrame
    window.requestAnimFrame = (function(callback) {
        return window.requestAnimationFrame || 
               window.webkitRequestAnimationFrame || 
               window.mozRequestAnimationFrame || 
               window.oRequestAnimationFrame || 
               window.msRequestAnimationFrame || 
               function(callback) {
                   window.setTimeout(callback, 1000 / 60);
               };
    })();

    // 获取Canvas上下文
    const canvas = document.getElementById('myCanvas');
    const ctx = canvas.getContext('2d');
    // 存储所有矩形的数组
    const rects = [];

    // 点击按钮生成新矩形
    $('#addRect').click(function() {
        rects.push({
            x: canvas.width, // 初始位置在Canvas右侧外
            y: Math.random() * (canvas.height - 50), // 随机垂直位置
            width: 50,
            height: 50,
            speed: 2 + Math.random() * 3, // 随机移动速度
            color: `rgb(${Math.floor(Math.random()*255)}, ${Math.floor(Math.random()*255)}, ${Math.floor(Math.random()*255)})`
        });
    });

    // 动画循环函数
    function animate() {
        // 清空Canvas
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // 遍历所有矩形,更新位置并绘制
        for(let i = rects.length - 1; i >= 0; i--) {
            const rect = rects[i];
            // 左移更新x坐标
            rect.x -= rect.speed;
            // 绘制矩形
            ctx.fillStyle = rect.color;
            ctx.fillRect(rect.x, rect.y, rect.width, rect.height);

            // 如果矩形完全移出左边缘,从数组中移除(优化性能)
            if(rect.x + rect.width < 0) {
                rects.splice(i, 1);
            }
        }

        // 继续下一帧动画
        requestAnimFrame(animate);
    }

    // 启动动画循环
    animate();
});

关键说明

  • 为什么不用克隆Canvas?因为所有矩形的绘制都可以在同一个Canvas上下文里完成,多个Canvas反而会增加DOM复杂度和性能消耗,完全没必要。
  • 用数组管理矩形状态:每个矩形是一个独立的对象,包含位置、尺寸、速度、颜色等属性,动画循环里统一更新和绘制,逻辑清晰又容易维护。
  • 移出边缘后移除矩形:避免数组里积累大量已不可见的对象,优化动画性能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:34:43