onload vs onLoad(区分大小写)

时间:2012-10-29 03:00:49

标签: javascript html5 canvas

我在网页中有2个函数(js),用于将图像附加到画布元素:

 function attachImage(tile, x, y)
    {
      base_image = new Image();
      base_image.src = 'Images/tiles/'+(tile-1)+'.png';
      base_image.onload = function(){
        context.drawImage(base_image, 32*x,32*y);
      }
    }

然后我将其复制并粘贴并复制到另一个画布

  function attachImage2(tile2, x2, y2)
    {
        base_image2 = new Image();
        base_image2.src = 'Images/tiles/'+(tile2-1)+'.png';
        base_image2.onLoad = function(){
            context2.drawImage(base_image2, 32*x2,32*y2);
      }
    }

在Firefox上,如果我创建一个onload而另一个onLoad,那么它可以正常工作。但无论我对chrome做什么,它都无法正确加载图像。

编辑:这是firefox和chrome之间的图像比较:

FIREFOX:http://imgur.com/JaEgy

CHROME:http://imgur.com/VJc6q

1 个答案:

答案 0 :(得分:5)

您应该使用onload小写)。

一些一般性说明

  • 当您需要本地变量时,请使用var
  • 您应该在实际设置onload之前设置src,否则({em>缓存)图像可能无法调用onload
  • 由于您的方法执行相同的操作,因此您应该只使用一个,并将上下文作为参数传递

所以

<script>
var canvas = document.getElementById('map');
context = canvas.getContext('2d');

var canvas2 = document.getElementById('map2');
context2 = canvas2.getContext('2d');

function attachImage(tile, x, y, canvasContext)
{
  var base_image = new Image();
  base_image.onload = function(){
    canvasContext.drawImage(base_image, 32*x,32*y);
  }
  base_image.src = 'Images/tiles/'+(tile-1)+'.png';
}
</script>

并且您不应为每次调用创建script标记

<?php
echo("<script>");
for($tr = 0; $tr < count($mapArray)-1; $tr++) {
    for($tc = 0; $tc < count($mapArray[$tr])-1; $tc++) {
        $tile = $mapArray[$tr][$tc];
        echo "attachImage(" . $tile . "," . $tc . "," . $tr . ",context);";
    }
}

for($tr = 0; $tr < count($mapArrayy)-1; $tr++) {
    for($tc = 0; $tc < count($mapArrayy[$tr])-1; $tc++) {
        if($mapArrayy[$tr][$tc]!=0){
            echo "attachImage(" . $mapArrayy[$tr][$tc]. "," . $tc . "," . $tr . ",context2);";
        }
    }
}
echo("</script>");
?>