Reputation:
I'm trying to create an animation in javascript.
I created a canvas
<canvas id = "animation" width="1130" height="222"></canvas>
and what I want to do, is to add 3 images (+1 more which is the background), and during each second I want to have 1 image shown and the other 2 hidden. What I have now is:
var canvas = document.getElementById('animation');
context = canvas.getContext('2d');
background = new Image();
background.src = 'images/background.png';
background.onload = function(){
context.drawImage(background, 0, 0);
}
var image1 = new Image();
image1.src = 'images/image1.png';
image1.onload = function(){
context.drawImage(image1, 895, 61);
}
var image2 = new Image();
image2.src = 'images/image2.png';
image2.onload = function(){
context.drawImage(image2, 895, 61);
}
var image3 = new Image();
image3.src = 'images/image3.png';
image3.onload = function(){
context.drawImage(image3, 895, 61);
}
image1.style.visibility = "visible";
image2.style.visibility = "hidden";
image3.style.visibility = "hidden";
setTimeout(function(){
image1.style.visibility = "hidden";
image2.style.visibility = "visible";
image3.style.visibility = "hidden";
}, 1000);
setTimeout(function(){
image1.style.visibility = "hidden";
image3.style.visibility = "visible";
image2.style.visibility = "hidden";
}, 2000);
setTimeout(function(){
image3.style.visibility = "hidden";
image1.style.visibility = "visible";
image2.style.visibility = "hidden";
}, 3000);
however it does not work. All of them appear on the screen
Upvotes: 0
Views: 87
Reputation: 549
You are trying to mix two different things here: canvas and CSS.
The canvas works like (surprise!) a canvas: that means that once you draw something there it will stay there until you draw something else over it. Therefore, changing the css of the images on memory will have no effect.
You have two alternatives: the DOM route, just insert the images in the DOM without the canvas and you will be able to change their style, or the Canvas route, calling to context.drawImage INSIDE various setTimeout
, so you draw a new image each second.
Upvotes: 1