为什么图像会被覆盖?

时间:2015-07-05 07:21:27

标签: javascript canvas

我正在学习Javascript和Canvas。在这种情况下请帮助我。我想用几个冒号画一行图像,最后一个总是覆盖前一个。

以下是示例:

  function main(){
     contains Canvas creating
        canvas = document.createElement('canvas');
    canvas.width = WIDTH;
    canvas.height = HEIGHT;
    ctx = canvas.getContext('2d');

    document.body.appendChild(canvas);

     and init();
    }

// Row是我的构造函数,带有坐标和drawImage方法。 DrawImage接受图像数组;

function Row(x,y){
            var _this = this;
            _this.x = x;
            _this.y = y;

            this.drawImage = function(img2){

                img.onload = function(){
                    for(var i = 0; i < img2.length; i+=1){
                    ctx.drawImage(img2[i], _this.x, this.y + i * canvas.height / 4, canvas.width / 5, canvas.height / 4);
                    console.log(_this.x);

                    };
                };
            };
        };

//例如,我创建两行并设置不同的坐标。如果帆布,我希望他们在不同的方面;         var first = new Row(0,0);         var second = new Row(350,0);

   function init(){

        loadImage(imgArray);

        // IMG is the arrays with images links
        // New instances takes the different coordinates, but the last is overwriting the previous. Why?

        first.drawImage(IMG);
        second.drawImage(IMG);


    };

1 个答案:

答案 0 :(得分:2)

当您致电first.drawImage时,会设置img.onload处理程序。当您调用second.drawImage时,这会覆盖img.onload处理程序。请尝试使用img.addEventListener('load', ...),以便调用两个回调。