用 HTML5 Canvas 建立圖案


使用以下方法用 HTML5 Canvas 建立圖案:createPattern(影像,重複)- 該方法將使用影像建立圖案。第二個引數可以是一個字串,其值之一:repeat、repeat-x、repeat-y 和 no-repeat。如果指定空字串或空值,則重複將被認為是。示例

示例

你可以嘗試執行以下程式碼來了解如何建立圖案 −

<!DOCTYPE HTML>
<html>
   <head>
      <style>
         #test {
            width:100px;
            height:100px;
            margin: 0px auto;
         }
      </style>
      <script>
         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');
               
               // create new image object to use as pattern
               var img = new Image();
               img.src = 'images/pattern.jpg';
               img.onload = function(){
                  // create pattern
                  var ptrn = ctx.createPattern(img,'repeat');
                  ctx.fillStyle = ptrn;
                  ctx.fillRect(0,0,150,150);
               }
            } else {
               alert('You need Safari or Firefox 1.5+ to see this demo.');
            }
         }
      </script>
   </head>
   <body id = "test" onload = "drawShape();">
      <canvas id = "mycanvas"></canvas>
   </body>
</html>

更新於:2020 年 3 月 4 日

383 次瀏覽

開啟你的事業

完成課程後取得認證

開始學習
廣告
© . All rights reserved.