我写了一个 canvas js 程序,但是如果我在 ubuntu 13.04 chromium 中使用 DOM 元素,它就不起作用(在 firefox 23.0 中很好)。这是代码:
<body>
<canvas id="map" width="600" height="600"></canvas>
<img id="photo" src="jiuwo.jpg" style="display:none;">
<img id="frame" src="frame.png" style="display:none;">
</body>
<script type="text/javascript">
function drawGallary(){
var canvas = document.getElementById('map');
if(canvas.getContext){
var ctx = canvas.getContext('2d');
var img1 = document.getElementById('photo');
var img2 = document.getElementById('frame');
ctx.drawImage(img1, 300, 300, 100, 100, 20, 21, 100, 100); // block of image
ctx.drawImage(img2, 0, 0);
}
}
</script>
我发现如果我把 drawImage 放到 onload 函数中,效果很好:
function drawGallary2(){
var canvas = document.getElementById('map');
if(canvas.getContext){
var ctx = canvas.getContext('2d');
var img1 = new Image();
img1.src = "jiuwo.jpg";
img1.onload = function(){
ctx.drawImage(img1, 300, 300, 100, 100, 20, 21, 100, 100);
}
var img2 = document.getElementById('frame');
img2.onload = function(){
ctx.drawImage(img2, 0, 0);
}
}
}
如果使用 DOM 元素作为图像源,是否需要 onload?谢谢。