【问题标题】:How to move the canvas backward in javascript?如何在javascript中向后移动画布?
【发布时间】:2021-11-11 08:18:46
【问题描述】:

我试着想盒子在达到 1000px (canvas.width) 时如何向后移动,但我不知道它在 if 条件后如何解决,所以有我的脚本,任何人都可以帮助我吗?

var canvas = document.querySelector("canvas");
var canvasCT = canvas.getContext("2d");
var x = 50;

function draw() {
    canvas.width = canvas.width;
    canvasCT.fillStyle = "blue";
    canvasCT.fillRect(x, 50, 100, 100);
}

function run() {
    draw();
    x += 5 ;
    if (x > 1000) {
    ......
    }
}
setInterval(run, 10);

【问题讨论】:

  • 一旦超过 1000,您需要开始从 x 每个循环中减去 5 而不是添加它。

标签: javascript html jquery canvas web-frontend


【解决方案1】:

var canvas = document.querySelector("canvas");
var canvasCT = canvas.getContext("2d");
var x = 50;
var speed = 5;

function draw() {
    canvas.width = canvas.width;
    canvasCT.fillStyle = "blue";
    canvasCT.fillRect(x, 50, 100, 100);
}

function run() {
    draw();
    x += speed;
    if (x > 1000 || x < 0) {
      speed = -speed;
    }
}
setInterval(run, 10);
&lt;canvas width=1000&gt;&lt;/canvas&gt;

【讨论】:

    猜你喜欢
    • 2014-03-17
    • 1970-01-01
    • 2021-12-30
    • 2014-01-12
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 2014-03-09
    • 2021-09-02
    相关资源
    最近更新 更多