使用createPattern方法的时候,图片大小比canvas大,怎么自动缩放?就让图片百分百在canvas里面显示?
图片比canvas的宽高大的时候可以创建一个新的canvas来把图片画上去,然后再将该canvas作为createPattern的图片放上去,代码如下:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 800;
var into = document.createElement("canvas");
var ctx2 = into.getContext('2d');
into.width = 50;
into.height = 50;
var img = new Image();
img.src = '1.jpg';
img.onload = function() {
ctx2.drawImage(img,0,0,50,50);
var pattern = ctx.createPattern(into, 'no-repeat');
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, 800, 800);
}