简体   繁体   中英

html5 canvas background img

when i write a img to the back ground of a canvas it works but if i refresh it disapears please help this is a really annoying bug in my page. heres a sample bit of code that is doing it

<img id="back" src="back.jpg" alt="background" width="200" height="300">
<canvas id="myCanvas" width="300" height="400" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("back");
ctx.drawImage(img,0,0);


ctx.moveTo(20,375);
ctx.lineTo(150,375);
ctx.stroke();

ctx.moveTo(70,375);
ctx.lineTo(70,50);
ctx.stroke();

ctx.moveTo(70,120);
ctx.lineTo(130,50);
ctx.stroke();

ctx.moveTo(70,50);
ctx.lineTo(180,50);
ctx.stroke();

ctx.moveTo(180,50);
ctx.lineTo(180,100);
ctx.stroke();


</script>

By the time your script executes, the image might not yet be loaded. Run your drawing code from the onload event of the image to make sure it happens only after it's been loaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM