2016-04-03 118 views
0

我遵循W3学校教程,并最终编写下面的代码,不做的复制图像内的画布元素的工作。 Canvas是空白......html画布绘制图像不工作

<img id="image" src="assets/images/bw.jpg" width="200" height="276" alt="" /> 
<canvas id="canvas" width="220" height="286"></canvas> 

和Javascript如下:

var c=document.getElementById("canvas"); 
var ctx=c.getContext("2d"); 
var img = document.getElementById("image"); 
ctx.drawImage(img,0,0); 

为什么这个简单的例子是不工作???

+1

你要等待图像加载然后才能在画布上绘制它。 – Kaiido

+0

不,我有window.onLoad –

+0

这是在** l ** oad与减l。如果接受的解决方案确实解决了您的问题,请向您的浏览器填写错误报告。 – Kaiido

回答

0

尝试包括 width, height.drawImage()呼叫;这是

实际的解决方案,耐心指出的@Kaiido,就是用onload事件属性附加到<img>元素

<img id="image" onload="draw()" src="http://lorempixel.com/50/50" width="200" height="276" alt="" /> 
<canvas id="canvas" width="220" height="286"></canvas> 
<script> 
    function draw() { 
    var c=document.getElementById("canvas"); 
    var ctx=c.getContext("2d"); 
    var img = document.getElementById("image"); 
    ctx.drawImage(img,0,0); 
    } 
</script> 

HTMLImageElement.addEventListener("load", handler)

+0

美丽。谢谢:) –

+1

除非图像的宽度和高度设置为0,这绝对不是问题! drawImage的destinationX和destinationY选项默认为图像大小。 @ daniel.tosaba你的问题在于你并没有等待onload事件。它现在正在工作,因为图像被缓存。 – Kaiido

+0

@Kaiido _“你的问题是你没在等待onload事件。”_你正在引用哪个'onload'事件? 'img'或'window'? – guest271314