首頁  >  文章  >  web前端  >  使用HTML5 Canvas建立一個圖案

使用HTML5 Canvas建立一個圖案

PHPz
PHPz轉載
2023-09-02 14:57:02654瀏覽

使用HTML5 Canvas创建一个图案

使用下列方法透過 HTML5 Canvas 建立圖案:createPattern(image, repetition)− 此方法將使用圖片來建立圖案。第二個參數可以是具有以下值之一的字串:repeat、repeat-x、repeat-y 和 no-repeat。如果指定空字串或 null,則將假定重複。

範例

您可以嘗試執行以下程式碼來了解如何建立一個模式 -

<!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(&#39;mycanvas&#39;);
           
            // Make sure we don&#39;t execute when canvas isn&#39;t supported
            if (canvas.getContext){
               // use getContext to use the canvas for drawing
               var ctx = canvas.getContext(&#39;2d&#39;);
               
               // create new image object to use as pattern
               var img = new Image();
               img.src = &#39;images/pattern.jpg&#39;;
               img.onload = function(){
                  // create pattern
                  var ptrn = ctx.createPattern(img,&#39;repeat&#39;);
                  ctx.fillStyle = ptrn;
                  ctx.fillRect(0,0,150,150);
               }
            } else {
               alert(&#39;You need Safari or Firefox 1.5+ to see this demo.&#39;);
            }
         }
      </script>
   </head>
   <body id = "test" onload = "drawShape();">
      <canvas id = "mycanvas"></canvas>
   </body>
</html>

以上是使用HTML5 Canvas建立一個圖案的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除