如何將影像用於 HTML5 canvas?


HTML5 <canvas> 標籤用於利用指令碼繪製圖形、動畫等。它是 HTML5 中引入的新標籤。要將影像用於 HTML5 畫布,請使用 drawImage() 方法。此方法會將給定影像繪製到畫布上。

可以嘗試執行以下程式碼來學習如何將影像用於 HTML 畫布。此處,image 是對影像或畫布物件的一個引用。x 和 y 構成目標畫布上的座標,我們的影像應置於此處。

示例

即時演示

<!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>

更新於:25-2 月-2020

367 次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.