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.