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>
有帮助吗?

解决方案

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', ...).

其他提示

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);
}

"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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top