Reputation: 726
I want to place an image in a HTML5 canvas. I found some sample code which worked, but the image was loaded 2 times when I actually only need 1. I can hide one of the images with JavaScript or CSS, but I'm looking for a way where the image only needs to load once.
<!DOCTYPE html>
<html>
<body>
<img id="img" src="img.png" width="150px" height="150px">
<canvas id="canvas" width="200px" height="200px"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img = document.getElementById("img");
ctx.drawImage(img, 0, 0);
</script>
</body>
</html>
Upvotes: 0
Views: 1616
Reputation:
The image's drawn twice, because you create node first and then redraw it to the canvas. but using above code image can not be scale fit use this below code to draw the image on canvas with responsive to canvas
<div id="worldmap" style="height=100%;width=100%">
<canvas id="myStaticMap"></canvas>
<div>
var canvas = document.getElementById("myStaticMap"),
ctx = canvas.getContext("2d");
canvas.width = $("#worldmap").width();
canvas.height = $("#worldmap").height();
ctx.drawImage(mapImage, 0, 0, canvas.width, canvas.height);
Upvotes: 0
Reputation: 907
The image's drawn twice, because you create <img../>
node first and then redraw it to the canvas.
Just remove <img id="img" src="img.png" width="150px" height="150px">
and add this to your JavaScript code:
img = new Image();
img.src = 'img.png';
img.onload = function(){
ctx.drawImage(img, 0, 0);
}
Upvotes: 3