How to pass parameters into image load event?

后端 未结 4 1637
一向
一向 2020-12-08 19:54

When I set the src of an image object, it will trigger an onload function. How can I add parameters to it?

x = 1;
y = 2;
imageObj = new Image();
imageObj.src         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 20:33

    Make a small function that handles it. Local variables will hold the correct scope.

    function loadImage( src, x, y) {
    
        var imageObj = new Image();
        imageObj.src = src;
        imageObj.onload = function() {
            context.drawImage(imageObj, x, y);
        };
    
    }
    
    var x = 1,
        y = 2;
    
    loadImage("foo.png", x, y);
    x = 3;
    y = 4;
    

提交回复
热议问题