Canvas 位图填充

来源:互联网 发布:记录工作时间的软件 编辑:程序博客网 时间:2024/06/07 00:23
一 位图填充方法
1、调用createPattern方法创建位图填充,该方法返回一个CanvasPattern对象。
2、将CanvasPattern对象赋值给CanvasRenderingContext2D的fillStyle或StrokeStyle属性。
二 代码
<!DOCTYPE html><html><head><meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" /><meta http-equiv="Content-Type" content="text/html; charset=GBK" /><title> 位图填充 </title></head><body><h2> 位图填充 </h2><canvas id="mc" width="400" height="280"style="border:1px solid black"></canvas><script type="text/javascript">// 获取canvas元素对应的DOM对象var canvas = document.getElementById('mc');// 获取在canvas上绘图的CanvasRenderingContext2D对象var ctx = canvas.getContext('2d');ctx.save();ctx.translate(30 , 20);var image = new Image();image.src = "wjc.gif";image.onload = function(){// 创建位图填充imgPattern = ctx.createPattern(image, "repeat");// 设置使用位图填充作为填充颜色ctx.fillStyle = imgPattern;// 填充一个矩形ctx.fillRect(0 , 0 , 160 , 80);// 恢复坐标系统ctx.restore();// 平移坐标系统ctx.translate(280 , 160)ctx.beginPath();// 添加圆弧ctx.arc(0 , 0  , 80 , 0 , Math.PI * 2 , true);ctx.closePath();ctx.lineWidth = 12;// 设置使用位图填充作为边框颜色ctx.strokeStyle = imgPattern;ctx.stroke();}</script></body></html>
 
三 运行结果

 
原创粉丝点击