HTML drawImage不适用于chrome。我尝试了所有的技巧

时间:2013-11-20 22:29:15

标签: javascript html html5 canvas

我注意到我的绘图功能不适用于Chrome,在firefox中一切正常并且绘制功能:

   Map.prototype.generate = function(){
        var ctx = document.createElement("canvas").getContext("2d");        
        ctx.canvas.width = this.width;
        ctx.canvas.height = this.height;    

        var rows = ~~(this.width/32);
        var columns = ~~(this.height/32);

        var imageObject = document.createElement("img");
        imageObject.src='ground.png';


        for (var i = 0; i < rows; i++) {        
            for (var j=0; j <columns; j++) {  
                ctx.drawImage(imageObject,i*32,j*32,32,32); 
            }   
        }       

        // store the generate map as this image texture
        this.image.src = ctx.canvas.toDataURL("image/jpg");                 

        // clear context
        // ctx = null;
    }

关于它为什么只能在Firefox中运行的任何想法?

1 个答案:

答案 0 :(得分:1)

尝试进行此更改:

   var imageObject = document.createElement("img");

   /// create a reference to current 'this'
   var me = this;

   /// need this as loading is async
   imageObject.onload = function() {    

       for (var i = 0; i < rows; i++) {        
           for (var j=0; j <columns; j++) {  
               console.log("1");
               /// use 'this' = image
               ctx.drawImage(this, i*32,j*32,32,32); 
           }   
       }       

       // store the generate map as this image texture
       /// 'me' as 'this' is here the image
       me.image.src = ctx.canvas.toDataURL("image/jpg");                 
   }

   imageObject.src='ground.png';