所谓平铺,指的是用按一定比例缩小的图像填满画布。HTML5中通过调用画布上下文对象的createPattern方法实现图像平铺,该方法应用格式为:createPattern(image,type)
其中参数image为被平铺对象,type表示图像平铺方式。type可取值有四种。
类型 | 说明 |
---|---|
no-repeat | 不平铺图像 |
repeat-x | 水平方向平铺图象 |
repeat-y | 垂直方向平铺图像 |
repeat | 全方向平铺图像 |
案例:
<fieldset>
<legend>图像平铺</legend>
<canvas id="canvas" width="500px" height="500px"></canvas>
<br>
<button onclick="draw(1)">横向平铺</button>
<button onclick="draw(2)">纵向平铺</button>
<button onclick="draw(3)">全向平铺</button>
</fieldset>
<script>
function draw(i) {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img = new Image();
img.src = "img.jpg";
img.onload = function() {
if (i == 1) {
ctx.fillStyle = ctx.createPattern(img, "repeat-x")
} else if (i == 2) {
ctx.fillStyle = ctx.createPattern(img, 'repeat-y');
} else {
ctx.fillStyle = ctx.createPattern(img, 'repeat');
}
ctx.fillRect(0, 0, canvas.width, canvas.height); //填充画布
}
}
</script>