如何使用 HTML5 canvas 中的圖片?
HTML5 <canvas> 標籤用於透過指令碼繪製圖形、動畫等。它是 HTML5 中引入的一個新標籤。若要將圖片與 HTML5 canvas 一起使用,請使用 drawImage() 方法。此方法將給定的圖片繪製到 canvas 上。
你可以嘗試執行以下程式碼,瞭解如何在 HTML Canvas 中使用圖片。這裡,圖片是對圖片或 canvas 物件的引用。x 和 y 形成目標 canvas 上我們應該放置圖片的座標。
示例
<!DOCTYPE HTML> <html> <head> <script type="text/javascript"> function drawShape() { // get the canvas element using the DOM var canvas = document.getElementById('mycanvas'); // Make sure we don't execute when canvas isn't supported if (canvas.getContext) { // use getContext to use the canvas for drawing var ctx = canvas.getContext('2d'); // Draw shapes var img = new Image(); img.src = '/images/backdrop.jpg'; img.onload = function() { ctx.drawImage(img,0,0); ctx.beginPath(); ctx.moveTo(30,96); ctx.lineTo(70,66); ctx.lineTo(103,76); ctx.lineTo(170,15); ctx.stroke(); } } else { alert('You need Safari or Firefox 1.5+ to see this demo.'); } } </script> </head> <body onload="drawShape();"> <canvas id="mycanvas"></canvas> </body> </html>
廣告