Html5中使用canvas 实现矩形和线条的绘制

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

让我们看看使用了fillRect,strokeRect clearRect 和其他的例子:

1
2
3
4
5
6
7
8
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() 结束自定义图形绘制。下面是一个绘制三角形的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 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();  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值