Javascript game collision detection wall - javascript

I've been following W3schools tutorial on creating a JavaScript game in a canvas https://www.w3schools.com/graphics/game_obstacles.asp
I've got to the stage where they add an obstacle in. Currently, it has collision detection which stops the game when it hits the wall. I am trying to figure out a way to treat it like a wall where the box could hit it and no longer move that direction and continue the game, making the wall work.
I've previously tried detecting what direction hit the wall and stopping movement that direction, but when I hold down an arrow key it moves through it.
Heres what I've got so far: https://jsfiddle.net/j9cy1mne/1/
<body onload="startGame()">
<script>
var myGamePiece;
var myObstacle;
var speed = 3;
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120);
myObstacle = new component(10, 200, "green", 300, 120);
myGameArea.start();
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop: function() {
clearInterval(this.interval);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
}
function updateGameArea() {
if (myGamePiece.crashWith(myObstacle)) {
console.log("crash");
} else {
myGameArea.clear();
myObstacle.update();
myGamePiece.x += myGamePiece.speedX;
myGamePiece.y += myGamePiece.speedY;
myGamePiece.update();
}
}
document.onkeydown = checkKeyD;
function checkKeyD(e) {
e = e || window.event;
if (e.keyCode == '38') {
// up arrow
myGamePiece.speedY = -speed;
} else if (e.keyCode == '40') {
// down arrow
myGamePiece.speedY = speed;
} else if (e.keyCode == '37') {
// left arrow
myGamePiece.speedX = -speed;
} else if (e.keyCode == '39') {
// right arrow
myGamePiece.speedX = speed;
}
}
document.onkeyup = clearmove;
function clearmove() {
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
}
</script>
</body>

The problem is here:
if (myGamePiece.crashWith(myObstacle)) {
console.log("crash");
} else {
In a real physics engine you detect collisions then you resolve collisions. The simplest "resolve collision" would be to move the piece back to the place it was before the crash. Something like:
if (myGamePiece.crashWith(myObstacle)) {
resolveCollision(myGamePiece, myObstacle);
} else {
But to do this you'll need to modify your physics engine, and your movement function to use a velocity vector. That means that instead of function checkKeyD(e) moving the piece, that function sets a velocity vector. Then crashWith() will determine if the position plus the velocity vector is going to crash and resolve collision will un-crash it.

Related

Basic keyboard functionality for movement of object

I am unable to figure out what is wrong with my code. I have another example I was able to get to work but it didn't use constructor objects and this one does. That's about the only different I can think of. I've tweaked it in many ways but no luck. Please help me understand why it isn't working.
function newGame() {
let Player, Controller;
let context = document.getElementById("canvas").getContext("2d");
//Player
Player = function (x, y, width, height) {
this.width = width,
this.height = height,
this.x = x,
this.y = y,
this.xVelocity = 0;
this.yVelocity = 0;
this.update = function () {
context.fillStyle = "red";
context.fillRect(this.x + this.xVelocity, this.y + this.yVelocity, this.width, this.height);
};
};
let player1 = new Player(200, 200, 25, 25);
let playerUpdate = function () {
player1.update();
};
//Controller
Controller = function() {
this.right = false;
this.left = false;
this.keyDownUp = function(e) {
let keyInput = (e.type == "keydown") ? true : false;
console.log(keyInput)
switch (e.keyCode) {
case 37:
this.left = keyInput;
break;
case 39:
this.right = keyInput;
}
}
};
let loop = function () {
if (Controller.left) {
player1.xVelocity += 10;
};
playerUpdate();
};
window.requestAnimationFrame(loop);
window.addEventListener("keydown", Controller.keyDownUp);
window.addEventListener("keyup", Controller.keyDownUp);
}
newGame();
Your loop only runs once. requestAnimationFrame(loop); is like setTimeout you need to call it for each frame. Add the line requestAnimationFrame(loop); at the bottom of the function loop.
Example
function loop() {
if (Controller.left) {
player1.xVelocity += 10;
}
playerUpdate();
requestAnimationFrame(loop); // get next frame
};
requestAnimationFrame(loop); // start animation
Re comments
The code is a mess and I am unsure as to your intentions in parts of it.
I have re-written it as follows making guesses as to your intentions.
(() => {
function Player(x, y, width, height) {
this.width = width,
this.height = height,
this.x = x,
this.y = y,
this.vx = 0;
this.vy = 0;
}
Player.prototype = {
update() {
this.vx = controller.left ? -10 : 0;
this.vx = controller.right ? 10 : this.vx;
this.x += this.vx;
this.y += this.vy;
this.x = (this.x + ctx.canvas.width) % ctx.canvas.width;
},
draw() {
ctx.fillStyle = "red";
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
function Controller() {
this.right = false;
this.left = false;
addEventListener("keydown", keyEvent.bind(this));
addEventListener("keyup", keyEvent.bind(this));
function keyEvent(e) {
if (e.code === "ArrowRight") { this.right = e.type === "keydown" }
else if (e.code === "ArrowLeft") { this.left = e.type === "keydown" }
}
}
function loop() {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
player.update();
player.draw();
requestAnimationFrame(loop);
};
const ctx = document.getElementById("canvas").getContext("2d");
const controller = new Controller();
const player = new Player(200, 175, 25, 25);
requestAnimationFrame(loop);
})();
<canvas id="canvas" width="300" height="200"></canvas>
Take what you can from it.

Javascript wall physics and ground physics

After the element or game-piece collides with the wall it stops moving. How can i reset the collision detection so that after the game-piece collides with the wall it is still able to move? Also after the game-piece collides with the ground it stops moving to. So how can i reset that collision detection so that it can move after colliding with the wall?
var myGamePiece;
var myObstacle;
var e = e || window.event;
var speed = 3;
var gravity = 0.05;
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120);
myObstacle = new component(10, 200, "green", 300, 120);
myGameArea.start();
myGameArea.gravityPhysics();
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
gravityPhysics: function() {
myGamePiece.speedY = -speed;
},
stop: function() {
clearInterval(this.interval);
}
};
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
this.hitBottom();
};
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + this.width;
var mytop = this.y;
var mybottom = this.y + this.height;
var otherleft = otherobj.x;
var otherright = otherobj.x + otherobj.width;
var othertop = otherobj.y;
var otherbottom = otherobj.y + otherobj.height;
var crash = true;
if (
mybottom < othertop ||
mytop > otherbottom ||
myright < otherleft ||
myleft > otherright
) {
crash = false;
}
return crash;
};
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
if (
myGameArea.canvas.height - this.height &&
myGamePiece.key == 38
) {
this.y = this.speedY;
}
this.gravitySpeed = 0; // reset?
}
};
}
function updateGameArea() {
if (myGamePiece.crashWith(myObstacle)) {
console.log("crash");
} else {
myGameArea.clear();
myObstacle.update();
myGamePiece.x += myGamePiece.speedX;
myGamePiece.y -= myGamePiece.speedY;
myGamePiece.update();
}
if (
myGameArea.gravityPhysics() &&
e.keyCode == document.addEventListener("keydown")
) {
myGamePiece.speedY = gravity - 10;
e.keyCode = true;
}
}
document.onkeydown = checkKeyD;
document.onkeyup = gravityPhysics;
function checkKeyD(e) {
if (e.keyCode == "38") {
// up arrow
myGamePiece.speedY = speed;
} else if (e.keyCode == "40") {
// down arrow
myGamePiece.speedY = -speed;
} else if (e.keyCode == "37") {
// left arrow
myGamePiece.speedX = -speed;
} else if (e.keyCode == "39") {
// right arrow
myGamePiece.speedX = speed;
}
}
if ((e = e || (window.event && window.event == false))) {
myGamePiece.speedY -= gravity;
}
function clearmove() {
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
}

Rotating an image around a fixed position - plain javascript

I've looked at several threads, and I cannot for the life of me get my image to properly rotate to the position of my mouse cursor. I can get the image to translate to the position of my mouse cursor, I know I'm close, I just don't know exactly where I am off at... below is what I have so far. The image needs to rotate at its current position and face the mouse cursor if that makes more sense... PS I am new to coding!
var myGamePiece;
function startGame() {
myGamePiece = new component(50, 50, "Assets/PNG/Soldier 1/soldier1_gun.png", 10, 120, "image"); //size, source, starting location
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 1);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function() {
clearInterval(this.interval);
}
}
function component(width, height, color, x, y, type) {
this.type = type;
if (type == "image") {
this.image = new Image();
this.image.src = color;
}
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
this.width = window.innerWidth/20; //update width based on window size
this.height = window.innerHeight/20; //update height based on window size
ctx = myGameArea.context;
if (type == "image") {
document.onmousemove = function(e) {
dx = e.pageX;
dy = e.pageY;
console.log(e.pageX, e.pageY);
theta = Math.atan2(dy - this.y, dx - this.x);
theta = theta * (180/Math.PI);
}
//console.log(theta);
ctx.save();
ctx.translate(this.image.width/2,this.image.height/2); // updates the image origin upon rotating
ctx.rotate(theta); // rotates the image to specified position
ctx.drawImage(this.image,
this.x,
this.y,
this.width, this.height);
ctx.restore();
} else {
console.log("failed");
}
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.newPos();
myGamePiece.update();
}
function moveup() {
myGamePiece.speedY = -1;
}
function movedown() {
myGamePiece.speedY = 1;
}
function moveleft() {
myGamePiece.speedX = -1;
}
function moveright() {
myGamePiece.speedX = 1;
}
function clearmove() {
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
}
var keys;
setInterval(mainLoop, 50);
function mainLoop(){
document.addEventListener("keydown", function (e) {
keys = (keys || []);
keys[e.keyCode]=true;
if (keys[37]){ // left
moveleft();
}
if (keys[38]){ // up
moveup();
}
if (keys[39]){ // right
moveright();
}
if (keys[40]){ // down
movedown();
}
} , false);
document.addEventListener("keyup", function (e) {
keys[e.keyCode]=false;
stop();
clearmove();
if (keys[37]){ // left
moveleft();
}
if (keys[38]){ // up
moveup();
}
if (keys[39]){ // right
moveright();
}
if (keys[40]){ // down
movedown();
}
}, false);
}

How do I use drawimage() on an obstacle.push in an HTML canvas game? [duplicate]

This question already has answers here:
Bing Maps API v8 - pushpin SVG URI image
(1 answer)
JavaScript Failed to execute 'drawImage'
(3 answers)
Uncaught TypeMismatchError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D'
(1 answer)
Failed to execute 'drawImage' on 'CanvasRenderingContext2D'
(1 answer)
Closed 5 years ago.
When trying to draw an image on an obstacle in an html canvas game I get this error message: Uncaught InvalidStateError: Failed to execute 'drawimage' on 'CanvasRenderingContext2D': The HTMLImageElement provided is in the 'broken' state.
The obstacle is invisible but the game still stops if the player collides with where it should be. The other stationary obstacles' images in the game are visible. What do I do?
I tried uploading the images in my html to let them load before using them but it still doesn't work. Other articles about similar situations do not cover this same context and do not help me who is quite new to programming.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" type="text/css" href="stylesheet.css"> <link/>
</head>
<body onload="startGame()">
<h2> My Lost Game </h2>
<p>Press the 'up', 'down', 'left' and 'right' keys on your keyboard to move. Avoid the obstacles and reach the goal.</p><br>
<p></p>
<script>
var myObstacle = [];
function startGame() {
myGameArea.start();
myGameGoal = new component(75, 95, "player2.jpg", 710, 215, "image");
myGamePiece = new component(75, 95, "player.jpg", 10, 215, "image");
myObstacle2 = new component (110, 150, "obstacle2.jpg", 350, 0, "image");
myObstacle3 = new component (110, 150, "obstacle3.jpg", 530, 350, "image");
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 800;
this.canvas.height = 500;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[4]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
myGameArea.keys = (myGameArea.keys || []);
myGameArea.keys[e.keyCode] = true;
})
window.addEventListener('keyup', function (e) {
myGameArea.keys[e.keyCode] = false;
})
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);},
stop : function() {
clearInterval(this.interval);
}
}
function component(width, height, color, x, y, type) {
this.type = type;
if (type == "image") {
this.image = new Image();
this.image.src = color;
}
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
if (type == "image") {
ctx.drawImage(this.image,
this.x,
this.y,
this.width, this.height);
} else {
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) ||
(mytop > otherbottom) ||
(myright < otherleft) ||
(myleft > otherright)) {
crash = false;
}
return crash;
}
}
function updateGameArea() {
var x, y;
for (i = 0; i < myObstacle.length; i += 1) {
if (myGamePiece.crashWith(myObstacle[i])) {
myGameArea.stop();
return;
}
}
myGameArea.clear();
myGameArea.frameNo += 1;
if (myGameArea.frameNo == 1 || everyinterval(150)) {
x = 200;
y = 300;
myObstacle.push(new component(110, 150, "obstacle1.jpg", x, y, "image"));
}
for (i = 0; i < myObstacle.length; i += 1) {
myObstacle[i].y += -1;
myObstacle[i].update();
}
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.speedX = -3; }
if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.speedX = 3; }
if (myGameArea.keys && myGameArea.keys[38]) {myGamePiece.speedY = -3; }
if (myGameArea.keys && myGameArea.keys[40]) {myGamePiece.speedY = 3; }
myObstacle2.update();
myObstacle3.update();
myGameGoal.update();
myGamePiece.newPos();
myGamePiece.update();
}
function everyinterval(n) {
if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
return false;
}
</script>
</body>
</html>

Canvas map with looping background images

I am working on Browser game, and I wanted to make map where you can move around, fight with mobs, buy some stuff, but only map. Everything else will be in different pages.
So I made map with multiple images which are in loop.
It reads value world, x and y from database. I have made it work with ajax so the page doesnt refresh every time you move, but I wanted to make this map using Canvas.
$ystart = $y - 2;
$ymax = $y + 2;
$xstart = $x - 3;
$xmax = $x + 3;
for($y=$ystart;$y<=$ymax;$y++){
echo "<tr>";
for($x=$xstart;$x<=$xmax;$x++){
// echo "<td><img src=images/map/day/".$x."_".$y.".jpg width=100 height=100 border=0></td>\n";
if($x==$posx and $y==$posy){
echo "<td background=images/map/world_".$world."/".$y."_".$x.".jpg><img src=images/char.png width=100 height=100 border=0></td>";
} else{
echo "<td><img src=images/map/world_".$world."/".$y."_".$x.".jpg width=100 height=100 border=0></td>";
}
}
echo "</tr>";
}?>
I have done this so far
body {
margin: 0;
}
canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
<body onload="startGame()">
<script>
var myGamePiece;
var myUpBtn;
var myDownBtn;
var myLeftBtn;
var myRightBtn;
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120);
myUpBtn = new component(30, 30, "blue", 50, 10);
myDownBtn = new component(30, 30, "blue", 50, 70);
myLeftBtn = new component(30, 30, "blue", 20, 40);
myRightBtn = new component(30, 30, "blue", 80, 40);
myGameArea.start();
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('mousedown', function(e) {
myGameArea.x = e.pageX;
myGameArea.y = e.pageY;
})
window.addEventListener('mouseup', function(e) {
myGameArea.x = false;
myGameArea.y = false;
})
window.addEventListener('touchstart', function(e) {
myGameArea.x = e.pageX;
myGameArea.y = e.pageY;
})
window.addEventListener('touchend', function(e) {
myGameArea.x = false;
myGameArea.y = false;
})
window.addEventListener('keydown', function(e) {
myGameArea.key = e.keyCode;
})
window.addEventListener('keyup', function(e) {
myGameArea.key = false;
})
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.clicked = function() {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var clicked = true;
if ((mybottom < myGameArea.y) || (mytop > myGameArea.y) || (myright < myGameArea.x) || (myleft > myGameArea.x)) {
clicked = false;
}
return clicked;
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.x && myGameArea.y) {
if (myUpBtn.clicked()) {
myGamePiece.y -= 1;
}
if (myDownBtn.clicked()) {
myGamePiece.y += 1;
}
if (myLeftBtn.clicked()) {
myGamePiece.x += -1;
}
if (myRightBtn.clicked()) {
myGamePiece.x += 1;
}
}
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.key && (myGameArea.key == 37 || myGameArea.key == 65)) {
myGamePiece.speedX = -1;
}
if (myGameArea.key && (myGameArea.key == 39 || myGameArea.key == 68)) {
myGamePiece.speedX = 1;
}
if (myGameArea.key && (myGameArea.key == 38 || myGameArea.key == 87)) {
myGamePiece.speedY = -1;
}
if (myGameArea.key && (myGameArea.key == 40 || myGameArea.key == 83)) {
myGamePiece.speedY = 1;
}
myGamePiece.newPos();
myUpBtn.update();
myDownBtn.update();
myLeftBtn.update();
myRightBtn.update();
myGamePiece.update();
}
</script>
</body>
But I can't figure out how to make this background loop in canvas based on x and y position and how to make it change when you move.
I'm trying to learn about canvas myself, so I've been browsing through these questions. I thought yours would be a fun exercise to try.
Basically, I'm creating an object, and moving it at each iteration. I will constantly check the x position of my object. And depending on its value, I can change the background image.
Try this and see for yourself. Try moving your right arrow key and then left arrow key. You will notice the background image changes.
var canvas = document.getElementById("my-canvas");
var ctx = canvas.getContext("2d");
canvas.style.backgroundImage = "url('http://cdn.wonderfulengineering.com/wp-content/uploads/2014/07/background-wallpapers-26.jpg')";
function hero(x, y) {
this.x = x;
this.y = y;
this.moveLeft = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
this.x -= 5;
drawHero(this.x, this.y);
};
this.moveRight = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
this.x += 5;
drawHero(this.x, this.y);
};
this.moveUp = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
this.y -= 5;
drawHero(this.x, this.y);
}
this.moveDown = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
this.y += 5;
drawHero(this.x, this.y);
}
}
function drawHero(x,y) {
ctx.fillStyle = "red";
ctx.fillRect(x, y, 10, 10);
}
var hero1 = new hero(40, 40);
ctx.fillStyle = "red";
ctx.fillRect(40, 40, 10, 10);
window.addEventListener("keydown", function(event) {
if (event.keyCode == 38) {
hero1.moveUp();
}
else if (event.keyCode == 37) {
hero1.moveLeft();
}
else if (event.keyCode == 39) {
hero1.moveRight();
}
else {
hero1.moveDown();
}
});
setInterval(function() {
if (hero1.x <= 100) {
canvas.style.backgroundImage = "url('http://cdn.wonderfulengineering.com/wp-content/uploads/2014/07/background-wallpapers-26.jpg')";
}
else if (hero1.x > 100 && hero1.x <= 200) {
canvas.style.backgroundImage = "url('https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRi2F1v1PXpOEYScFCbvmsV-74C573z8tFBvIPXwDO8d1KImpJ09Q')";
}
else {
canvas.style.backgroundImage = "url('https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSOSNoN1aLzWvpwrENvqPb4tKgzfeeqlMsUeC0fjdGABXXLdLIo')";
}
},50);
#my-canvas {
border: 1px solid black;
}
<canvas id="my-canvas" width="400" height="400"></canvas>

Categories