【问题标题】:Only one image being drawn to canvas只有一张图像被绘制到画布上
【发布时间】:2015-03-13 23:14:47
【问题描述】:

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

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() 函数,则另一个会显示,但如果我将它们都“激活”,则只会显示后一个。所以基本上,一个新的图像被绘制,但旧的图像被删除。

【问题讨论】:

    标签: javascript canvas


    【解决方案1】:

    您正在使用全局声明的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 以了解如何按顺序加载图像,以及在完成后按顺序绘制它们。

    【讨论】:

    • 嘘!非常感谢先生。
    • @Robert 很高兴我能帮上忙! .)
    猜你喜欢
    • 2012-01-14
    • 2022-08-03
    • 1970-01-01
    • 2016-07-08
    • 2014-09-03
    • 2013-11-01
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多