createPattern
是 Canvas API 中的一个方法,用于创建一个具有重复图像的样式。
一、基本用法
要使用 createPattern
方法,需要先让画布绑定一个图像。例如:
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var image = new Image();
image.src = 'pattern.png';
var pattern = ctx.createPattern(image, 'repeat');
ctx.fillStyle = pattern;
这样就创建了一个用图像 pattern.png
填充的样式。其中,'repeat'
参数表示重复方式,可以是:
'repeat'
:水平和垂直方向都重复;'repeat-x'
:只重复水平方向;'repeat-y'
:只重复垂直方向;'no-repeat'
:不重复。canvas.getContext
方法返回的是一个CanvasRenderingContext2D
对象,而createPattern
方法则是该对象的一个方法。我们可以将其返回的填充样式设置给fillStyle
属性,从而对画布进行填充。
二、设置图片大小
1. stretch
当我们使用线性渐变或放射性渐变时,可以使用设置大小的方式对渐变进行调整。但是 createPattern
方法只是重复填充图像,如果需要对图像进行大小调整,可以使用以下代码:
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var image = new Image();
image.src = 'pattern.png';
image.onload = function() {
var pattern = ctx.createPattern(image, 'no-repeat');
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, canvas.width, canvas.height);
var newPattern = ctx.createPattern(image, 'no-repeat');
ctx.fillStyle = newPattern;
ctx.scale(2, 2);
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
在此代码中,通过调用 CanvasRenderingContext2D
对象的 scale
方法,将画布横向和纵向都放大了一个倍数,从而使得图案填充的矩形区域也相应地放大了。
2. repeat
在上面的代码中,我们使用了 'no-repeat'
,也就是说图像只填充了一次。如果想要图像在填充时也能够重复,可以使用以下代码:
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var image = new Image();
image.src = 'pattern.png';
image.onload = function() {
var pattern = ctx.createPattern(image, 'repeat');
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, canvas.width, canvas.height);
var newPattern = ctx.createPattern(image, 'repeat');
ctx.fillStyle = newPattern;
ctx.scale(2, 2);
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
在此代码中,我们将填充重复方式改为了 'repeat'
,从而使得图案可以重复填充。
三、自定义图案
除了使用图像作为填充样式外,我们也可以使用 Canvas API 的其他方法来创建自定义的图案。
1. 矩形
使用 CanvasRenderingContext2D
对象的 fillRect
方法,可以绘制一个填充的矩形。
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'blue';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'yellow';
ctx.fillRect(0, 0, canvas.width / 2, canvas.height / 2);
ctx.fillRect(canvas.width / 2, canvas.height / 2, canvas.width / 2, canvas.height / 2);
在此代码中,我们先绘制了一个蓝色的矩形背景,然后在其上绘制了两个黄色的矩形。自定义的图案就是由多个正方形组成的。
2. 圆形
使用 CanvasRenderingContext2D
对象的 arc
方法,可以绘制一个填充的圆形。
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var radius = 50;
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var startAngle = 0;
var endAngle = Math.PI * 2;
ctx.fillStyle = 'blue';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(centerX, centerY, radius, startAngle, endAngle);
ctx.fillStyle = 'yellow';
ctx.fill();
在此代码中,我们先绘制了一个蓝色的矩形背景,然后在其上绘制了一个黄色的圆形。自定义的图案就是一个圆形。