【问题标题】:HTML Canvas How can I get the rectangle to move backwards?HTML Canvas 如何让矩形向后移动?
【发布时间】:2022-01-06 06:32:25
【问题描述】:

我的下面的代码会在我启动矩形时为矩形设置动画。我怎样才能让它同时向左生长?我已经尝试过 (line.x -= line.dx) 和其他一些变体,但它似乎不起作用。

   const line = {
        x: 600,
        y: 100,
        width: 1,
        height: 3,
        dx: 1,
        dy: 1,
    }

    let totalLineWidth = line.x + line.width;

    const drawLine = () => {
      ctx.fillRect(line.x, line.y , line.width, line.height)
    }


    const update = () => {

        drawLine()

        line.x += line.dx


    
        requestAnimationFrame(update)
    }
    update()

【问题讨论】:

    标签: css reactjs html5-canvas


    【解决方案1】:

    在向右绘制一个新位的同时,向左侧绘制一个新位。

    左边的新位与右边的新位相同。这就是 (600 - (left.x - 600) - 如果你改变起始位置,当然更新 600。

    在整个页面中运行这个sn-p,然后单击按钮开始绘图。

    const canvas = document.querySelector('canvas');
    const ctx = canvas.getContext('2d');
    const line = {
      x: 600,
      y: 100,
      width: 1,
      height: 3,
      dx: 1,
      dy: 1,
    }
    
    let totalLineWidth = line.x + line.width;
    
    const drawLine = () => {
      ctx.fillRect(line.x, line.y, line.width, line.height);
      ctx.fillRect(600 - (line.x - 600), line.y, line.width, line.height);
    }
    
    
    const update = () => {
    
      drawLine()
    
      line.x += line.dx
    
    
    
      requestAnimationFrame(update)
    }
    //removed just for demo so we can wait until user clicks the button
    //update()
    canvas {
      background-color: pink;
      /* just for demo so we can see where the canvas is */
    }
    <button onclick="update(); this.style.display = 'none';">Click me to start</button>
    <br>
    <canvas width=1200 height=200></canvas>

    【讨论】:

    • 一个后续问题,现在我如何计算左边的线何时达到左边的宽度?我尝试做 line.x -= line.dx 并记录“命中”,但它不起作用。似乎 line.x += line.dx 和 line.x -= line.dx 相互抵消。当任一击中 canvas.width 时,我需要它来注册“击中”。
    • 这太琐碎了,我想知道我是否理解正确。让我知道我是否误解了!只是当您发现自己想要将下一张图纸放在
    • 你实际上解决了我最初的问题,所以谢谢你!但是现在,当我增加 line.x += line.dx 的行时,它只占右侧。我也试图检测左侧的碰撞。 if(line.x + line.width> canvas.width) { console.log('右击') } else if( (600 - (line.x -600))
    • 抱歉,我不确定是什么问题 - 有问题吗?例如,您是否在左侧之前击中右侧。
    猜你喜欢
    • 2023-03-02
    • 2013-12-29
    • 2016-09-14
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 2018-06-11
    相关资源
    最近更新 更多