HTML5 之Canvas标签学习笔记之二:绘制矩形

在真正开始之前,我们需要先探讨 canvas 的网格(grid)或者坐标空间(coordinate space)。如 HTML 里有一个150像素宽, 150像素高的 canvas 对象。我在画面上叠加上默认网格,如右图。通常网格的1个单元对应 canvas 上的1个像素。网格的原点是定位在左上角(坐标(0,0))。画面里的所有物体的位置都是相对这个原点。这样,左上角的蓝色方块的位置就是距左边x像素和 距上边Y像素(坐标(x, y))

步骤:

1, 取得canvas元素  (document.getElementById)

2, 取得上下文 (context)

上下文是一个封装了很多绘图功能的对象。需要把使用canvas对象的getContext方法来获得图形上下文。将参数设置为"2d",不能为“3d” or "4d".

3, 填充与绘制边框

fill(填充),stroke(绘制边框)

4, 设定绘图样式 (默认为黑色#000000)

  所谓绘图样式,主要是针对图形的颜色而言的,但是并不限于图形的颜色。

  fillStyle ----填充的样式,在该属性中填入填充的颜色值

  strokeStyle ----图形边框的样式。在该属性中填入边框的颜色值

5, 指定线宽

使用图形上下文对象的lineWidth属性设置图形边框的宽度。在绘制图形的时候,任何直线都可以通过lineWidth属性来指定

6, 指定颜色值 (主要针对的是矩形,方法如4)

7, 绘制矩形

分别使用fillRect方法 与 strokeRect方法来填充矩形和绘制矩形边框

context.fillRect (x,y,width,height)

context.strokeRect(x,y,width,height)

还有一个方法,擦除指定矩形区域的图形,变为透明

context.clearRect(x,y,width,height)

x--起点横坐标   y--起点纵坐标   width---矩形宽度   height---矩形高度

综上所述,通过getContext来取得图形上下文,通过fillStyle属性与strokeStyle属性来指定颜色,通过fillRect方法与strokeRect方法来绘制图形,就可以绘制出简单的图形了。

 

代码

 

<! DOCTYPE html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
      function drawShape(){
        // get the canvas element using the DOM
        var canvas = document.getElementById('tutorial');

        // 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
	  ctx.fillStyle="#666666";		 
          ctx.fillRect(25,25,100,100);
	  ctx.strokeStyle = "#00f";
          ctx.clearRect(45,45,60,60);
          ctx.strokeRect(50,50,50,50);
		  
        } else {
          alert('You need Safari or Firefox 1.5+ to see this demo.');
        }
      }
    </script>
    <style type="text/css">

    </style>
  </head>

  <body onload="drawShape();">
  
    <div>
      <canvas id="tutorial" width="150" height="150"></canvas>
	</div>
</body>
</html>

 效果图

参考资料

https://developer.mozilla.org/zh-CN/docs/Canvas_tutorial/Drawing_shapes   

《HTML5与CSS3权威指南》

posted @ 2012-11-28 13:06  开心豆豆  阅读(2853)  评论(0编辑  收藏  举报