由于一开始是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平铺的代码详解的详细内容。
