in this code i used onload function but it is not still display image on canvas, why???
<!DOCTYPE HTML>
<开发者_JAVA百科html>
<body>
<canvas id="myCanvas" width="100" height="200" style="border:5px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript">
var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
var img=new Image();
img.onload = function(){
// execute drawImage statements here};
cxt.drawImage(img,0, 0, 50, 50, 0, 0);
}
img.src = "myimg.png";
</script>
</body>
</html>
Maybe I'm missing something, but I don't see any onload
. And I think you're missing some arguments. As far as I know, drawImage takes 3, 5, or 9 arguments. Since you're at 7, you're probably looking for the nine argument function.
Try:
<html>
<head>
<script type="text/javascript">
function init() {
var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
var img=new Image();
img.onload = function(){
// execute drawImage statements here;
// drawImage( src, sx,sy, sw, sh, dx, dy, dw, dh ); <-- 9 arg form.
// src = the img (new Image();)
// sx, sy, sw, sh = The rectangle to draw to.
// dx, dy = Where to position it.
// dw, dh = Width and height to scale to.
cxt.drawImage(img,0, 0, 50, 50, 0, 0, 50, 50);
}
img.src = "myimg.png";
}
window.onload = init;
</script>
</head>
<body>
<canvas id="myCanvas" width="100" height="200" style="border:5px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
</body>
</html>
Hope that helps. For a better look at how to use canvas
with images, try visiting:
http://diveintohtml5.ep.io/canvas.html#images
I'm not sure exactly what you are trying to achieve but to just display the image here's some simplified code:
<script type="text/javascript">
var c=document.getElementById("myCanvas").getContext("2d");
var img=new Image();
img.src = 'myimg.png';
img.onload = function(){
// execute drawImage statements here
c.drawImage(img,0,0);
}
</script>
You're original code is correct except for the drawImage() call which requires either two more arguments, or you can drop all except the first three.
You also don't need to hook the window.onload event because the JavaScript is being executed in the body element which has the same effect so the answer directing you to do that whilst correct, isn't required.
Here is your code with the fix in place:
<!DOCTYPE HTML>
<html>
<body>
<canvas id="myCanvas" width="100" height="200" style="border:5px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript">
var c = document.getElementById("myCanvas"),
cxt = c.getContext("2d"),
img = new Image();
img.onload = function(){
// Execute drawImage() statements here
cxt.drawImage(img, 0, 0, this.width, this.height, 0, 0, this.width, this.height);
}
img.src = "myimg.png";
</script>
</body>
</html>
精彩评论