Html5 drawImage 无法显示问题
最近开始看html5,看到html5 canvas 可以直接drawImage ,于是看着文档写了个demo,可是总是空白的,一开始以为路径问题,各种改路径,改图片位置,后来以为是我Chrome 浏览器的问题,于是换其他浏览器一样不显示,后来查了下,是因为图片没加载完成,所以在调用drawImage的方法的时候是空白的
<!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="500" height="300" style="border:1px solid #d3d3d3;background:#ffffff;"> Your browser does not support the HTML5 canvas tag. </canvas> <script type="text/javascript"> var c = document.getElementById("myCanvas"); var cxt = c.getContext("2d"); var img = new Image(); img.src = "assets/images/1.jpg"; cxt.drawImage(img,0,0); </script> </body> </html>
修改如下就可以了,说实话,html5确实比flex效率高了很多。
<!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="500" height="300" style="border:1px solid #d3d3d3;background:#ffffff;"> Your browser does not support the HTML5 canvas tag. </canvas> <script type="text/javascript"> var c = document.getElementById("myCanvas"); var cxt = c.getContext("2d"); var img = new Image(); img.src = "assets/images/1.jpg"; img.onload=function (){ cxt.drawImage(img,0,0); } </script> </body> </html>