只有一张图片被绘制到 canvas

Only one image being drawn to canvas

我有多个图像要绘制到 canvas,但一次只能绘制一个。谁能给我解释一下为什么?

JSON

"images": [
        {
            "name": "carat_white",
            "src": "images/CaretR-01.png",
            "x": 0,
            "y": 0,
            "dest_x": 548,
            "dest_y": 148,
            "width": 40,
            "height": 40
        },

        {
            "name": "carat_black",
            "src": "images/Caret-01.png",
            "x": 0,
            "y": 0,
            "dest_x": 700,
            "dest_y": 100,
            "width": 40,
            "height": 40
        }
    ]

JS

    var images = result[0].images;
    var imageObj = new Image();
    function drawImages(src, x, y, width, height, dest_x, dest_y, dest_width, dest_height){
        dest_width = (width / 2);
        dest_height = (height / 2);

         imageObj.onload = function(){
            ctx.drawImage(imageObj, x, y, width, height, dest_x, dest_y, dest_width, dest_height);
         }
         imageObj.src = src;
     }

drawImages(images[0].src, images[0].x, images[0].y, images[0].width, images[0].height, images[0].dest_x, images[0].dest_y, images[0].width, images[0].height);

drawImages(images[1].src, images[1].x, images[1].y, images[1].width, images[1].height, images[1].dest_x, images[1].dest_y, images[1].width, images[1].height);

如果我注释掉其中一个 drawImages() 函数,另一个会显示,但如果我将它们都保留 'active' 则只有后一个会显示。所以基本上,绘制了一张新图像,但删除了旧图像。

您正在使用全局声明 imageObj,这意味着每次调用 drawImages 时都会覆盖它。

改为将其放入函数中,并在 onload 处理程序中使用 this

function drawImages(src, x, y, width, height, dest_x, dest_y, dest_width, dest_height){

    var imageObj = new Image();

    dest_width = (width / 2);
    dest_height = (height / 2);

     imageObj.onload = function(){
        ctx.drawImage(this, x, y, width, height, dest_x, dest_y, dest_width, dest_height);
     }
     imageObj.src = src;
 }

如果需要存储引用,将其推送到全局数组:

var loadedImages = [];

function drawImages(src, x, y, width, height, dest_x, dest_y, dest_width, dest_height){

    var imageObj = new Image();
    loadedImages.push(imageObj);
    ...

注意:如果您使用它在彼此之上绘制图像,您需要记住,图像不一定按开始时的相同顺序完成加载(由于尺寸不同等原因)。

查看一个示例 this post 以查看如何按顺序加载图像,以及完成后按顺序绘制它们。