createPattern()方法是为元素在指定的方向上设置重复模式的方法,(通俗些讲就是在画布中设置元素的平铺模式),此方法返回一个CanvasPattern对象,语法如下:
ctx.createPattern(image, repetition);
image: 做为重复图像源的 CanvasImageSource 对象。可以是下列之一:
1. HTMLImageElement (),
2. HTMLVideoElement (),
3. HTMLCanvasElement (),
4. CanvasRenderingContext2D,
5. ImageBitmap,
6. ImageData, or a
7. Blob.
repeat: 指定如何重复图像,允许的值为:
1. “repeat” (如果是“”或者null时,默认为该值)
2. “repeat-x”
3. “repeat-y”
4. “no-repeat”
以图片为实例进行说明下:
HTML部分代码:
<canvas id="canvas" width="600" height="480" style="border: 1px #ccc dashed;" onclick="drawImg();">canvas>
js部分代码:
var count = 0; // 统计鼠标点击次数
var canvas = document.querySelector("canvas"), ctx = canvas.getContext("2d");
function drawImg(){
var strPrnType = "";
count++;
count = (count == 5) ? 1 : count;
switch(count) {
case 1: strPrnType = "no-repeat"; break;
case 2: strPrnType = "repeat-x"; break;
case 3: strPrnType = "repeat-y"; break;
case 4: strPrnType = "repeat"; break;
}
ctx.clearRect(0,0, canvas.width, canvas.height);
var img = new Image();
img.src = "http://yanyuans.com/demo/images/mg.png";
var prn = ctx.createPattern(img, strPrnType);
img.onload = function(){
ctx.fillStyle = prn;
ctx.fillRect(0,0, canvas.width, canvas.height);
}
}
createPattern()第一个参数可以是图片也可以是canvas等等,下面以canvas为例:
HTML部分:
<canvas id="canvas" width="600" height="480" style="border: 1px #ccc dashed;" onclick="drawImg();">canvas>
js部分:
var canvas = document.querySelector("canvas"), ctx = canvas.getContext("2d");
var pattern = document.createElement('canvas');
pattern.width = 40;
pattern.height = 40;
var pctx = pattern.getContext('2d');
pctx.fillStyle = "rgb(188, 222, 178)";
pctx.fill();
var pattern = ctx.createPattern(pattern, "repeat");
ctx.rect(0,0,200,200);
ctx.fillStyle = pattern;
ctx.fill();