Reputation: 21
In my simple test code (HTML and JavaScript) to place an image in a canvas, drawImage()
is not working. An image is created in the HTML page but not in the canvas. The code is:
const canvas = document.getElementById("myCanvas");
const img = document.getElementById("myImg");
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
function showPics(){
ctx.fillStyle = "red";
ctx.fillRect(0,0,50,50);
}
showPics();
<img id="myImg" src="https://picsum.photos/100/100" alt="Cannot find image" width="100" height="100">
<canvas id="myCanvas" width="150" height="175" style="border: 5px solid #000000;"></canvas>
In (Windows 10) Firefox upon opening the HTML file, the image is shown in the HTML page but not in the canvas. If I refresh, the image does appear in both the page and the canvas. In my Android 6 phone, the image appears in the HTML page but never in the canvas. Win10 Firefox screenshots are:
The impression I have is that the JavaScript code cannot find the image file even though the image file is in the same folder as the html code.
In (Windows 10) Firefox, what is refresh doing to allow the JavaScript to access the image file? In Android 6, why can't it find it at all?
Upvotes: 1
Views: 78
Reputation: 21
@Mike thanks for pointing me toward making sure the image was loaded. The following code works.
function showPics() {
const canvas = document.getElementById("myCanvas");
const img = document.getElementById("myImg");
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 50, 50);
}
<img
id="myImg"
src="https://picsum.photos/100/100"
alt="Cannot find image"
onload="showPics()"
width="100"
height="100"
/>
<canvas
id="myCanvas"
width="150"
height="175"
style="border: 5px solid #000000"
></canvas>
Upvotes: 1