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();
在此代碼中,我們先繪製了一個藍色的矩形背景,然後在其上繪製了一個黃色的圓形。自定義的圖案就是一個圓形。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/240832.html
微信掃一掃
支付寶掃一掃