Reputation: 121
I am trying to place multiple images on one canvas and move them upwards, as soon as they reach the top respawn at the bottom again.
This is my code:
var canvas = document.getElementById("canvas");
var context = canvas.getContext('2d');
function image(src) {
var x = Math.random() * (innerWidth - 94);
var y = 400;
var speed = (- Math.random() * (+5 - +1) +1);
//creating the image object
var image = new Image();
window.onload = function() {
//setting the source of the image to the passed in src param
image.src = src;
this.update = function() {
context.clearRect(0, 0, innerWidth, innerHeight);
context.beginPath();
context.drawImage(this.image, this.x, this.y, 94,229);
context.fill();
context.closePath();
if(this.y <= (-canvas.height)-30) {
this.y = 400;
this.x = Math.random() * (innerWidth - 100);
console.log("respawned" + x);
}
this.y += speed;
}}}
window.onload = function(){
createImages();
}
function createImages(){
var image1 = new image("../Website/Assets/sadballoon.png");
var image2 = new image("../Website/Assets/red.jpg");
//var images = [image1,image2];
setInterval(
function() {
image1.update();
image2.update();
console.log("calling update");
},10);
}
The error i am getting is Uncaught TypeError: image1.update is not a function which i understand that i am making an Image object and not the function image() object. How can i fix this?
Upvotes: 1
Views: 50
Reputation: 123
You could have the Image
object be a property of your image
class.
window.onload = function() {
function image(src) {
var x = Math.random() * (innerWidth - 94);
var y = 400;
var speed = (- Math.random() * (+5 - +1) +1);
var image = new Image(); //Creating the image property of our Image class to store an HTML Image object
image.src = src; //assigning the appropriate src to our image
this.update = function() {
context.clearRect(0, 0, innerWidth, innerHeight);
context.beginPath();
context.drawImage(this.image, this.x, this.y, 94,229);
context.fill();
context.closePath();
if(this.y <= (-canvas.height)-30) {
this.y = 400;
this.x = Math.random() * (innerWidth - 100);
console.log("respawned" + x);
}
this.y += speed;
}
}
function createImages(){
var image1 = new image("../Website/Assets/sadballoon.png");
var image2 = new image("../Website/Assets/red.jpg");
var images = [image1,image2];
setInterval(
function() {
image1.update();
image2.update();
},10);
}
var canvas = document.getElementById("canvas");
var context = canvas.getContext('2d');
createImages();
}
Upvotes: 2