【问题标题】:Why is the images overwriting?为什么图像会被覆盖?
【发布时间】:2015-07-05 15:35:47
【问题描述】:

我正在学习 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);


    };

【问题讨论】:

  • 可能是scope 问题,您必须详细说明如何创建canvas 以及如何获得ctx,看来您是全局声明的。
  • 我已经添加了。但没有什么特别的。也许是 Row 构造函数中的问题?

标签: javascript canvas


【解决方案1】:

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

【讨论】:

  • 哇!非常非常感谢你!我在构造函数中检查了所有地方,但甚至没有想到问题可能出在 onload 函数中。
猜你喜欢
  • 2017-05-08
  • 1970-01-01
  • 2010-10-17
  • 2015-06-25
  • 1970-01-01
  • 2012-05-29
  • 1970-01-01
  • 1970-01-01
  • 2014-06-05
相关资源
最近更新 更多