Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving the start position of canvas pattern

Tags:

html

canvas

I have a code:

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

How can i move the start position of pattern image?

like image 961
Glebka Avatar asked Oct 08 '11 18:10

Glebka


People also ask

How do I move the canvas position in HTML?

HTML | canvas moveTo() Method The canvas moveTo() method is used to move the path to the specified point in the canvas, without creating a line. After calling the moveTo() method, we can use stroke() method to draw the path on the canvas.

How do you move elements in canvas?

Moving elements to a different page To select multiple elements, hold Shift on your keyboard, and click to add other elements to the selection. Drag the elements to the new page thumbnail. You'll then be taken to it. Drag the elements into the canvas and position them on the page.

What is moveTo and Lineto in canvas?

Definition and UsageThe moveTo() method moves the path to the specified point in the canvas, without creating a line. Tip: Use the stroke() method to actually draw the path on the canvas. JavaScript syntax: context.moveTo(x,y);


2 Answers

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();
}
like image 83
Steve Hanov Avatar answered Oct 13 '22 06:10

Steve Hanov


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();
like image 41
cacheflowe Avatar answered Oct 13 '22 06:10

cacheflowe