0

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>
1
  • I only see the image displayed once when I use the code above under the <img> element. The canvas element is empty and does not contain the image at the moment. Am I missing something? Commented Dec 17, 2014 at 18:07

2 Answers 2

3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.