Canvas pattern offset

You can simply translate the context after drawing the line/shape & before stroking/filling to offset the pattern. Updated fiddle http://jsfiddle.net/28BSH/27/

ctx.fillStyle = somePattern;
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(180, 180);
ctx.save();
ctx.translate(offset, offset);
ctx.stroke();
ctx.restore();

Update Since this answer was posted there is now (since 2015/02) a local setTransform() on the CanvasPattern instance itself (see specs). It may not be available in all browsers yet (only Firefox supports it when this was written).

Method 1

You could offset the main canvas and add a delta value to the actual position of the line:

var offsetX = 10, offsetY = 10;
ctx.translate(offsetX, offsetY);
ctx.lineTo(x - offsetX, y - offsetY);
// ...

Example

(the demo only shows the pattern being translated, but of course, normally you would move the line together with it).

Line

etc. this way you cancel the translation for the line itself. But it introduces some overhead as the coordinates needs to be calculated each time unless you can cache the resulting value.

Method 2

The other way I can think of is to sort of create a pattern of the pattern it self. I.e. for the pattern canvas repeat the dot so that when you move it outside its boundary it is repeated in the opposite direction.

For example here the first square is the normal pattern, the second is the offset pattern described as method two and the third image uses the offset pattern for fill showing it will work.

The key is that the two patterns are of the same size and that the first pattern is repeated offset into this second version. The second version can then be used as fill on the main.

Example 2 (links broken)

Example 3 animated

Dots

var ctx = demo.getContext('2d'),
    pattern;

// create the pattern    
ctx.fillStyle = 'red';
ctx.arc(25, 25, 22, 0, 2*Math.PI);
ctx.fill();

// offset and repeat first pattern to base for second pattern
ctx = demo2.getContext('2d');
pattern = ctx.createPattern(demo, 'repeat');
ctx.translate(25, 25);
ctx.fillStyle = pattern;
ctx.fillRect(-25, -25, 50, 50);

// use second pattern to fill main canvas
ctx = demo3.getContext('2d');
pattern = ctx.createPattern(demo2, 'repeat');
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, 200, 200);

Tags:

Html

Canvas