Reputation: 1
I have JavaScript code.
<canvas id="view" width="120" height="120">
błąd
</canvas>
<script>
var _view = document.getElementById("view");
if(_view.getContext) {
var canvas = _view.getContext("2d");
var img = new Image();
img.src = "fajnetlo.png";
canvas.drawImage(img, 0, 0, 50, 50, 0, 0, 50, 50);
}
</script>
In the canvas image isn't displayable. Image and file is in one directory. Web browser rectangle etc. drawing, or image not. Why?
Upvotes: 0
Views: 2699
Reputation: 30153
<canvas id="view" width="120" height="120">
błąd
</canvas>
<script>
var view = document.getElementById("view");
var ctx= view.getContext("2d");
img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0, 50, 50, 0, 0, 50, 50);
}
img.src = 'fajnetlo.png';
</script>
Upvotes: 0
Reputation: 44826
Do the drawImage in the onLoad callback of the image. MDN quote:
When this script gets executed, the image starts loading. Trying to call drawImage before the image has finished loading will throw in gecko 1.9.2 and earlier, and silently do nothing in Gecko 2.0 and later. So you must use an onload event handler:
var img = new Image(); // Create new img element
img.onload = function(){
// execute drawImage statements here
};
img.src = 'myImage.png'; // Set source path
Source: https://developer.mozilla.org/en/Canvas_tutorial/Using_images
Upvotes: 4