using createPattern() with a canvas

I’m trying to get a repeating canvas pattern. Sadly all examples I could find repeat an image. So i tried this:

function init() {
var canvas = document.getElementById("bg");
var ctx = canvas.getContext("2d");

//creating a new canvas  
var canvas = document.createElement('canvas');
canvas.width = 500;
canvas.height = 400;
var img = canvas.getContext("2d");

draw(img);
var objPattern = ctx.createPattern(img, "repeat");
ctx.fillStyle = objPattern;
ctx.fillRect(0, 0, document.body.clientHeight, document.body.clientWidth);
}

function draw(img) {
  //img.save();
  img.beginPath();
  img.moveTo(0.0, 40.0);
  img.lineTo(26.9, 36.0);
  img.bezierCurveTo(31.7, 36.0, 36.0, 32.1, 36.0, 27.3);
  img.lineTo(40.0, 0.0);
  img.lineTo(11.8, 3.0);
  img.bezierCurveTo(7.0, 3.0, 3.0, 6.9, 3.0, 11.7);
  img.lineTo(0.0, 40.0);
  img.closePath();
  img.fillStyle = "rgb(188, 222, 178)";
  img.fill();
  img.lineWidth = 0.8;
  img.strokeStyle = "rgb(0, 156, 86)";
  img.lineJoin = "miter";
  img.miterLimit = 4.0;
  img.stroke();
  //img.restore();
}

and included it into the html file like this:

<body onload="init()">
<canvas id="bg" width=100%; height=100%;></canvas>
…

I don’t really want to use loops to repeat the pattern “by hand” using offsets as i feel(and hope) that there should be an easier approach. The save and restore in the draw code are used in some tutorials and examples, but they don’t really make any sense to me, so i commented them out.

Answer

Anything that takes an image in Canvas can take a Canvas element too.

Here is an example of your drawing code making a pattern, and a custom pattern function in case you want more fine-grained control:

<!-- HTML -->
<canvas id="canvas1" width="500" height="500"></canvas>
var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');



// set up a pattern
var pattern = document.createElement('canvas');
pattern.width = 40;
pattern.height = 40;
var pctx = pattern.getContext('2d');

pctx.beginPath();
pctx.moveTo(0.0, 40.0);
pctx.lineTo(26.9, 36.0);
pctx.bezierCurveTo(31.7, 36.0, 36.0, 32.1, 36.0, 27.3);
pctx.lineTo(40.0, 0.0);
pctx.lineTo(11.8, 3.0);
pctx.bezierCurveTo(7.0, 3.0, 3.0, 6.9, 3.0, 11.7);
pctx.lineTo(0.0, 40.0);
pctx.closePath();
pctx.fillStyle = "rgb(188, 222, 178)";
pctx.fill();
pctx.lineWidth = 0.8;
pctx.strokeStyle = "rgb(0, 156, 86)";
pctx.lineJoin = "miter";
pctx.miterLimit = 4.0;
pctx.stroke();

var pattern = ctx.createPattern(pattern, "repeat");
ctx.rect(0,0,200,200);
ctx.fillStyle = pattern;
ctx.fill();

The key thing to note here is that the created canvas is only 40×40 pixels, just large enough to hold the pattern.

http://jsfiddle.net/UxDVR/7/

Source: stackoverflow
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .