初次學習canvas,用來作筆記記錄下遇到的問題及解決方案html
這裏是要將一張圖片寫到canvas裏,按照網上搜索,初寫了段代碼,但是卻沒顯示,覺得是路徑問題,不能跨域名使用,後來改成相對路徑後,仍然無效,以下:canvas
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <img src="./ws.jpg" alt="" style="width: 100px;" id="imgDom"> <canvas id="myCanvas" width="300" height="300">Your browser does not support the HTML5 canvas tag.</canvas> <script> var can = document.getElementById("myCanvas"); var ctx = can.getContext("2d"); var imgDom = document.getElementById("imgDom"); ctx.drawImage(imgDom, 0, 0); </script> </body> </html>
後來通過搜索發現,是加載順序的緣由,很簡單對不對?在圖片沒加載完的時候,不會調用drawImage方法,上代碼:跨域
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <img src="http://static.huibuy.shop/tuiguang/zaozhuang/img1.jpg" alt="" style="width: 100px;" id="imgDom"> <canvas id="myCanvas" width="300" height="300">Your browser does not support the HTML5 canvas tag.</canvas> <script> var can = document.getElementById("myCanvas"); var ctx = can.getContext("2d"); var imgDom = document.getElementById("imgDom"); imgDom.onload = function() { ctx.drawImage(imgDom, 0, 0); } </script> </body> </html>
發現兩段代碼的不一樣了麼,就是img標籤上多了一個onload事件學習