I try to think how the box can move backward when it hit 1000px (canvas.width) ,but I don’t know how it solves after If condition, so there’s my script, anyone can help me ?
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);
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);
<canvas width=1000></canvas>