我有一个使用 context.fillRect() 方法绘制图像的方法。我希望重复绘制此图像,即沿 x 和 y 轴以平铺格式绘制,因为它的尺寸很小(长度为 15 像素)。
这是为了填充我的画布,宽度为 700 像素,高度为 500 像素。
这可以使用 context.createPattern() 方法来完成吗?如何?
我有一个使用 context.fillRect() 方法绘制图像的方法。我希望重复绘制此图像,即沿 x 和 y 轴以平铺格式绘制,因为它的尺寸很小(长度为 15 像素)。
这是为了填充我的画布,宽度为 700 像素,高度为 500 像素。
这可以使用 context.createPattern() 方法来完成吗?如何?
使用的秘诀context.createPattern
是context.fillStyle
属性。
首先,创建模式,然后将模式分配给context.fillStyle
,最后,context.fillRect
用于绘制模式:
// assuming img is loaded...
var ptrn = ctx.createPattern(img,'repeat');
ctx.fillStyle = ptrn;
ctx.fillRect(0,0, canvas.width,canvas.height);
MDN 上有一个完整的例子。
根据您对 apsillers 的回答,我建议您将所需的图案绘制到另一个画布元素上。然后,您可以将完成的绘图传递给ctx.createPattern
.
var drawing = document.createElement('canvas');
//Do necessary drawing
//ctx.fillRect(etc)
var ptrn = ctx.createPattern(drawing,'repeat');
ctx.fillStyle = ptrn;
ctx.fillRect(0,0, canvas.width,canvas.height);