我试图将多张图像放置在一张画布上,并在它们到达顶部后立即向上移动它们。
这是我的代码:
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);
}
我遇到的错误是未捕获的TypeError:image1.update不是一个函数 我知道我在做一个Image对象而不是函数image()对象。我该如何解决?
答案 0 :(得分:1)
您可以将Image
对象作为您的image
类的属性。
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();
}