问题
I am trying to show an image on a canvas at the top corner and the draw function is not working properly. What have I done wrong.
The above image is what I want to show on the screen.
<html>
<head>
<title></title>
</head>
<body>
<p><canvas id="canvas" style="border:1px solid black;" width="450" height="310"></canvas>
</body>
<script>
var c=document.getElementById("canvas");
var ctx=c.getContext("2d");
draw();
function draw(){
var img = new Image();
img.src = "t.gif";
ctx.drawImage(img,0,0);
}
</script>
</html>
回答1:
The problem is that you attempt to draw the image immediately, before the browser has finished downloading it.
Try this instead:
function draw(){
var img = new Image();
img.onload = function() {
ctx.drawImage(img,0,0);
};
img.src = "t.gif";
}
回答2:
You should draw image after it is loaded
img.onload = function() {
// here...
};
来源:https://stackoverflow.com/questions/25705121/why-is-my-image-not-showing-on-the-canvas