Asim Malik
Asim Malik

Reputation: 11

inserting image in html canvas code not working

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>

Upvotes: 0

Views: 104

Answers (2)

danny.hu
danny.hu

Reputation: 110

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

Upvotes: 1

C. S.
C. S.

Reputation: 823

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

Upvotes: 0

Related Questions