canvas not drawing images

久未见 提交于 2019-12-10 17:11:28

问题


I'm just trying to figure out how to get an image to draw on a canvas. I followed a tutorial on W3 schools, but when i tried it on my own it doesn't seem to be working. I copy and paste the code below into an HTML file, and the image never loads into the canvas. I downloaded the picture into the same directory. I've been asking around, and looked online, but no one seems to know what the problem is. I'm using an updated version of chrome (Version 29.0.1547.76 m).

<!DOCTYPE html>
<html>
<body>

<p>Image to use:</p>
<img id="scream" src="img_the_scream.jpg" alt="The Scream" width="220" height="277">

<p>Canvas:</p>
<canvas id="myCanvas" width="250" height="300" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
this.ctx.drawImage(img,10,10);

</script>

</body>
</html>

回答1:


Your image probably hasn't finished loading at the point you are using drawImage:

HTML

Add onload handler in img tag:

<img id="scream" onload="draw()" src="...

Then the function to handle it:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");

function draw() {
    ctx.drawImage(img,10,10);
}

Online demo here

Be aware of that where you place the scripts in your document matters as well.

I would recommend you setting the src attribute in JavaScript as well. That makes it more "safe" to handle the onload (or subscribed event with img.addEventListener('load', ...).




回答2:


you should use the following approach that first let the image loaded then display:

image.onload = function() {
    pic.getContext('2d').drawImage('your image to display', 0,0);
}



回答3:


"If you try to call drawImage() before the image has finished loading, it won't do anything (or, in older browsers, may even throw an exception). So you need to be sure to use the load event so you don't try this before the image has loaded."

example:

var img = new Image();   // Create new img element
img.addEventListener('load', function() {
  // execute drawImage statements here
}, false);
img.src = 'myImage.png'; // Set source path

Source



来源:https://stackoverflow.com/questions/19060751/canvas-not-drawing-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!