只有一个图像被绘制到画布上

时间:2015-03-13 15:08:34

标签: javascript 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()功能,则其他功能会显示,但如果我将它们保留为“活跃”状态。只有后一个显示。所以基本上,绘制了一个新图像,但删除了旧图像。

1 个答案:

答案 0 :(得分:0)

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

将其置于函数内部,并在this处理程序中使用onload

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);
    ...

注意:如果你使用它来绘制彼此之上的图像,你需要记住,图像不一定完成加载与它们开始时相同的顺序(由于不同的大小等)。 / p>

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