javascript - 为什么图像会被覆盖?

标签 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);

                    };
                };
            };
        };

//例如,我创建两行并设置它们不同的坐标。我希望它们位于 Canvas 的不同侧面; var 首先 = 新行(0, 0); var 第二 = 新行(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);


    };

最佳答案

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

关于javascript - 为什么图像会被覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31228051/

相关文章:

javascript - 使用 jquery .html() 获取元素本身的 html

javascript - 如何在调用异步函数后在 javascript/jquery 代码中创建暂停

javascript - 有什么理由不将配置绑定(bind)到 Node.js 中的全局对象?

JavaScript Canvas : How to get the specific points on transparent png file?

javascript - 我怎样才能创建一个阴影效果完全沿 Canvas 的顶部以外的所有侧面运行?

javascript - 如何在每个单元格中动态显示图表?

python - plot_surface : get the x, y,z值写在右下角

html - 为什么指定目标位置时 Canvas 的 putImageData 不起作用?

javascript - 如何使用 fabricjs 放大并居中对象?

javascript - 如何以数字和字母组合的形式显示javascript对象的值?