HTML5 Canvas - 使用影像



本教程將演示如何將外部影像匯入畫布,然後如何使用以下方法在該影像上繪製:

序號 方法和描述
1

beginPath()

此方法重置當前路徑。

2

moveTo(x, y)

此方法使用給定點建立一個新的子路徑。

3

closePath()

此方法將當前子路徑標記為已關閉,並使用與新關閉子路徑的起點和終點相同的點開始一個新的子路徑。

4

fill()

此方法使用當前填充樣式填充子路徑。

5

stroke()

此方法使用當前描邊樣式描邊子路徑。

6

drawImage(image, dx, dy)

此方法將給定的影像繪製到畫布上。這裡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>

它將產生以下結果:

html5_canvas.htm
廣告