0

i'm trying to insert an image in a canvas but my code does'nt seem to work. i'm getting a canvas with the appropriate background color but somehow the image does not get displayed. here is my code. Character on canvas .canvas1 { background-color:grey; border:1px solid; }

</head>
<body>
    <div id="imagediv">
        <img id="spear1" src="E:\html-files\spear.png" style="height:150px; width:150px" draggable="true" ondrag="drag()" >
    </div>
    <div id="canvasdiv">
        <canvas id="mainCanvas" class="canvas1" height="500px" width="600px"></canvas>
    </div>

    <script>
        var canvas=document.getElementById("mainCanvas");
        var ctx=canvas.getContext("2d");
        var img=document.getElementById("spear1");
        ctx.drawImage(img,0,0,160,160);

    </script>
</body>

3
  • 1
    possible duplicate of How to fetch image from system to load in canvas in html5 Commented Nov 26, 2013 at 11:28
  • 1
    You can drawImage, also from external location. You can't do "getImageData" though. But the problem here is that the image might not have been completely loaded yet Commented Nov 26, 2013 at 11:29
  • jsfiddle.net/Z4TfC Commented Nov 26, 2013 at 11:30

2 Answers 2

1

If you want to insert an image in a canvas, the image must have been loaded before inserted,so your code maybe look like that:

var canvas=document.getElementById("mainCanvas");
var ctx=canvas.getContext("2d");
var img=document.getElementById("spear1");
img.onload = function(){
     ctx.drawImage(img,0,0,160,160);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try to link the image with a relative path, or directly to an http://jsfiddle.net/combizs/5L7uL/.

Here is an example of linking to a file stored online

<img id="spear1" src="http://jamesmcgillis.com/upload/google_logo_001_small.jpg"...

If it does not work for you, make sure your browser supports canvas :-)

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.