1
function drawimage()
{
var f=document.getElementById("myCanvas");
    var cxt1=f.getContext("2d");
    var img1=new Image();
    img1.src="image.jpg";
    cxt1.drawImage(img1,0,0,750,400);
}

<canvas id="myCanvas" width="1125" height="600" style="border:1px solid #c3c3c3;">
</canvas>
<script type="text/javascript">

drawimage().

This is my javascript but when I am running this on browser, only border comes the 1st time and image appears only after refreshing the page. What is the problem with the code?

2 Answers 2

1

Try doing the image drawing in a "load" handler:

var img1=new Image();
img1.src="image.jpg";
img1.onload = function() {
  cxt1.drawImage(img1,0,0,750,400);
};
Sign up to request clarification or add additional context in comments.

4 Comments

is there same code for drawing lines also. On my page lines are sometimes drawn and sometimes after refresh.
Uhh ... lines? I don't know what you mean.
when i try to draw lines, sometimes they are drawn and some not
That sounds like something you should post as a different question.
0

the img1.src line MUST be after the onload because if the browser is fast enough (+ maybe image is cached or it's localhost), the image will be loaded just after img1.src is setted. In this case, the onload will not be called.

var img1=new Image();
img1.onload = function() {
  cxt1.drawImage(img1,0,0,750,400);
};
img1.src="image.jpg";

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.