免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1452 | 回复: 0
打印 上一主题 下一主题

canvas 教程(二)矩形和线条的绘制 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-12-22 08:54 |只看该作者 |倒序浏览

通过 fillStyle和 strokeStyle 属性可以轻松的设置矩形的填充和线条。颜色值使用方法和 CSS 一样:十六进制数、rgb()、rgba() 和 hsla。通过 fillRect可以绘制带填充的矩形。使用 strokeRect 可以绘制只有边框没有填充的矩形。如果想清除部分 canvas 可以使用 clearRect。上述三个方法的参数相同:x, y, width, height。前两个参数设定 (x,y) 坐标,后两个参数设置矩形的高度和宽度。可以使用 lineWidth属性改变线条粗细。让我们看看使用了fillRect,strokeRect clearRect 和其他的例子

  • context.fillStyle   = ‘#00f’; // blue   
  • context.strokeStyle = ‘#f00′; // red   
  • context.lineWidth   = 4;   
  • // Draw some rectangles.   
  • context.fillRect  (0,   0, 150, 50);   
  • context.strokeRect(0,  60, 150, 50);   
  • context.clearRect (30, 25,  90, 60);   
  • context.strokeRect(30, 25,  90, 60);  

此例子效果图见下图

路径

通过 canvas 路径(path)可以绘制任意形状。可以先绘制轮廓,然后绘制边框和填充。创建自定义形状很简单,使用 beginPath()开始绘制,然后使用直线、曲线和其他图形绘制你的图形。绘制完毕后调用 fill 和 stroke 即可添加填充或者设置边框。调用 closePath() 结束自定义图形绘制。下面是一个绘制三角形的例子:

  • // Set the style properties.   
  • context.fillStyle   = ‘#00f’;   
  • context.strokeStyle = ‘#f00′;   
  • context.lineWidth   = 4;   
  • context.beginPath();   
  • // Start from the top-left point.   
  • context.moveTo(10, 10); // give the (x,y) coordinates   
  • context.lineTo(100, 10);   
  • context.lineTo(10, 100);   
  • context.lineTo(10, 10);   
  • // Done! Now fill the shape, 和 draw the stroke.   
  • // Note: your shape will not be visible until you call any of the two methods.   
  • context.fill();   
  • context.stroke();   
  • context.closePath();  

其效果图见下图

另一个较复杂的例子中使用了直线、曲线和圆弧

您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP