由于一开始是drawImage出来的,所以采用了方法one
var canvas = document.getElementById("canvasId"); var ctx = canvas.getContext("2d"); var img = new Image(); //需要平铺的图片 img.src = "test1_bg.jpg"; img.onload = function (){ var can = document.createElement("canvas"); can.width = 10; can.height = 10; var ctx2 = can.getContext("2d"); ctx2.drawImage(img,0,0,10,10,0,0,10,10); ctx.fillStyle = ctx.createPattern(can,"repeat"); ctx.fillRect(0,0,200,200); }
用到了背景图的高宽度10,有点繁琐,为什么不一步到位呢?所以改成了这种方式
var canvas = document.getElementById("canvasId"); var ctx = canvas.getContext("2d"); var img = new Image(); //需要平铺的图片 img.src = "test1_bg.jpg"; img.onload = function (){ var pat = ctx.createPattern(img,"repeat"); ctx.rect(0,0,200,200); ctx.fillStyle = pat; ctx.fill(); }
GOOD!
再来重申下createPattern定义
createPattern() 方法在指定的方向内重复指定的元素。
元素可以是图片、视频,或者其他 <canvas> 元素。
被重复的元素可用于绘制/填充矩形、圆形或线条等等。
JavaScript 语法:
context.createPattern(image,"repeat|repeat-x|repeat-y|no-repeat");
参数 描述
repeat 默认。规定要使用的图片、画布或视频元素。 repeat-x 该模式只在水平方向重复。 repeat-y 该模式只在垂直方向重复。 no-repeat 该模式只显示一次(不重复)。
以上就是HTML5 canvas平铺的代码详解的详细内容,更多请关注Gxl网其它相关文章!
查看更多关于HTML5canvas平铺的代码详解的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did41236