我试图在一张画布上放置多张图像,并在它们到达顶部后立即向上移动它们,然后将它们向上移动。

这是我的代码:



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()对象。我怎样才能解决这个问题?

最佳答案

您可以将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();
}

关于javascript - 如何在 Canvas html内的多个图像上调用函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55327213/

10-16 21:59