我有一个代码:
function draw(ctx) {
// create new image object to use as pattern
var img = new Image();
img.onload = function(){
// create pattern
var ptrn = ctx.createPattern(img,'repeat');
ctx.fillStyle = ptrn;
ctx.fillRect(0,0,150,150);
}
img.src = 'images/wallpaper.png?' + new Date().getTime();
}
Run Code Online (Sandbox Code Playgroud)
如何移动图案图像的起始位置?
cac*_*owe 21
在回答接受的答案时:我会使用save()
&restore()
来避免潜在的问题,而不是撤消偏移量:
ctx.save();
ctx.translate(offset_x, offset_y);
ctx.fillRect(-offset_x, -offset_y, fill_x, fill_y);
ctx.restore();
Run Code Online (Sandbox Code Playgroud)
Xen*_*hyl 15
您可以通过翻译画布,在其上绘图,然后将其翻译回您开始的位置来实现此目的:
function draw(ctx) {
// create new image object to use as pattern
var img = new Image();
img.onload = function(){
// create pattern
var ptrn = ctx.createPattern(img,'repeat');
ctx.fillStyle = ptrn;
// offset vars
var offset_x = 60;
var offset_y = 75;
var fill_x = 500; // could be canvas.width
var fill_y = 500; // could be canvas.height
// offset
ctx.translate(offset_x, offset_y);
// draw
ctx.fillRect(-offset_x, -offset_y, fill_x, fill_y);
// undo offset
ctx.translate(-offset_x, -offset_y);
}
img.src = 'images/wallpaper.png?' + new Date().getTime();
}
Run Code Online (Sandbox Code Playgroud)