views:

417

answers:

2

For example, I have a canvas in a page with some kind of a path. It is created by javascript this way:

var context = $('#some_canvas').getContext('2d');
context.beginPath();
context.lineWidth = 5;
context.strokeStyle = '#000000';
context.moveTo(0, 0);
context.lineTo(100, 100);
context.stroke();

Is there a way to make the path that appears after this command to have some tiled background image?

+2  A: 

I believe you're looking for the createPattern() method:

var pattern = new Image;
pattern.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAARCAIAAABbzbuTAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAZtJREFUeNqMUs+rAVEUvjNG2MhClOUsppSEjbWFpOwtMIv5B2ZhZqkkZKkpe+XPYKtsbSxsZIGaQpgi4r3Pu5p3eV45dW/nnPt959zzg5RKpU6n8/WxkHq9LghCs9n8lICjKAohpFwuf0LgcCzLSqfTo9FIVVVd10He7XbX6/V8Pu/3e47jcB+Px0AgkEqlCOXNZjNJkgB1/wg+6XA4ACXPomkasXM1Gg3yj4AZi8WAHgwGgu1dLpcvOKRKJBLZbDaTyYDgdDrvXjtDLpd7yT6dTv8WzdNnaPP53A6Mezgc+v3+N/+jvO12GwwGqQfFYJRQksnker1+MwfIZDLxeDwA+Xy+xWIBT6VSgYk+Hg4HlvAoerVaodNQ8vl8KBSCUqvVAG2326g4EolsNhuYGNQjQ6/XAwh9GI/HbDxZltn/o2OPDBgctaPRKIsQRZEqWJxisXg3aaRCoQBvv99nw59Op3A4DH+1Wu12u09FYwh4w/6wBGwUOhuPx6FfLpfb7fZbtGEYpmnyPM/+x+v1tlotl8sFHdtFnd8CDACAg6Y2weEZQQAAAABJRU5ErkJggg==";
pattern.onload = function () {
    var context = $('#some_canvas').getContext('2d');
    context.beginPath();
    context.lineWidth = 16;
    context.strokeStyle = context.createPattern(pattern, 'repeat');
    context.moveTo(0, 0);
    context.lineTo(150, 150);
    context.stroke();
};
Ionuț G. Stan
Thanks, this is exactly what I was looking for!
Igor Zinov'yev
+1  A: 

Look into the globalCompositeOperation property of the canvas context. You should be able to draw your tiled background image (see the createPattern method), set the composite operation to 'destination-in' and then draw your path.

Richard M
Thanks for the link, I must have overlooked it earlier.
Igor Zinov'yev