HTML5 Canvas – 样式和颜色

HTML5 Canvas – 样式和颜色

HTML5 canvas 提供了以下两个重要属性来应用颜色到形状:

序号 方法和描述
1 fillStyle 此属性表示形状内部使用的颜色或样式。
2 strokeStyle 此属性表示形状周围线条使用的颜色或样式。

默认情况下,描边和填充颜色都设置为黑色,即CSS颜色值#000000。

fillStyle 示例

以下是一个简单的示例,它使用上述fillStyle属性创建了一个漂亮的图案。

<!DOCTYPE HTML>

<html>
   <head>

      <style>
         #test {
            width: 100px;
            height:100px;
            margin: 0px auto;
         }
      </style>

      <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');

               // Create a pattern
               for (var i = 0;i<7;i++) {

                  for (var j = 0;j<7;j++) {   
                     ctx.fillStyle = 'rgb(' + Math.floor(255-20.5*i)+ ','+ 
                     Math.floor(255 - 42.5*j) + ',255)';
                     ctx.fillRect( j*25, i* 25, 55, 55 );
                  }
               }
            } 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>
HTML

上面的示例将产生以下结果 −

HTML5 Canvas - 样式和颜色

strokeStyle 示例

以下是一个简单的示例,它使用上述fillStyle属性创建了另一个漂亮的图案。

<!DOCTYPE HTML>

<html>
   <head>

      <style>
         #test {
            width: 100px;
            height:100px;
            margin: 0px auto;
         }
      </style>
      <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');

               // Create a pattern
               for (var i = 0;i<10;i++) {

                  for (var j = 0;j<10;j++) {
                     ctx.strokeStyle = 'rgb(255,'+ Math.floor(50-2.5*i)+','+ 
                     Math.floor(155 - 22.5 * j ) + ')';
                     ctx.beginPath();
                     ctx.arc(1.5+j*25, 1.5 + i*25,10,10,Math.PI*5.5, true);
                     ctx.stroke();
                  }
               }
            } 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>
HTML

上述示例将产生以下结果−

HTML5 Canvas - 样式和颜色

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册