使用HTML5 Canvas创建一个图案

PHPz
发布: 2023-09-02 14:57:02
转载
654 人浏览过

使用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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!