开发者

Moving the start position of canvas pattern

开发者 https://www.devze.com 2023-04-11 12:07 出处:网络
I have a code: function draw(ctx) { // create new image object to use as pattern var img = ne开发者_JS百科w Image();

I have a code:

function draw(ctx) {
  // create new image object to use as pattern
  var img = ne开发者_JS百科w 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();
}

How can i move the start position of pattern image?


In response to the accepted answer: rather than undo the offset, I would use save() & restore() to avoid potential problems:

ctx.save();
ctx.translate(offset_x, offset_y);
ctx.fillRect(-offset_x, -offset_y, fill_x, fill_y);
ctx.restore();


You can achieve this by translating the canvas, drawing on it, and then translating it back to where you started:

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();
}


More general, complex transforms of the pattern alone are easily done. The trick is to do them immediately before the call to fill() or stroke().

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.beginPath();
        ctx.rect(0, 0, 150, 150);

        ctx.translate(-33, -33);
        ctx.fill();
    }

    img.src = 'images/wallpaper.png?' + new Date().getTime();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号