var cnv = document.getElementById('canvas');
var ctx = cnv.getContext('2d');
ctx.width = ctx.width; // Clear the context
// A quadratic curve fish that wll be used for the pattern.
var fishx = 240;
var fishy = 20;
ctx.save();
ctx.lineWidth = 1;
ctx.fillStyle = "#80FF00";
ctx.beginPath();
ctx.moveTo(fishx, fishy);
ctx.quadraticCurveTo(fishx + 10, fishy - 16, fishx + 18, fishy - 2);
ctx.quadraticCurveTo(fishx + 20, fishy - 2, fishx + 23, fishy - 8);
ctx.quadraticCurveTo(fishx + 23, fishy, fishx + 23, fishy + 8);
ctx.quadraticCurveTo(fishx + 20, fishy + 2, fishx + 18, fishy + 2);
ctx.quadraticCurveTo(fishx + 10, fishy + 16, fishx, fishy);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.restore();
// Convert an imagedata object into a canvas object.
function imageDataToCanvas(image) {
var cnvtmp = document.createElement("canvas");
cnvtmp.width = image.width;
cnvtmp.height = image.height;
var ctxtmp = cnvtmp.getContext("2d");
ctxtmp.putImageData(image, 0, 0);
return cnvtmp;
}
function drawPattern(x, y, rpt) {
// Create a pattern from the fish image.
var image = imageDataToCanvas(ctx.getImageData(fishx - 1, fishy - 9, 25, 18));
var pattern = ctx.createPattern(image, rpt);
ctx.fillStyle = pattern;
// Draw an outlined square showing the pattern
ctx.beginPath();
ctx.rect(x, y, 100, 100);
ctx.fill();
ctx.stroke();
}
// The top left coordinate of the pattern is measured from
// the screen origin (0, 0), so if the 'repeat-x', 'repeat-y'
// or 'no-repeat' value is used, the pattern will only be
// visible if the object being drawn overlaps a single instance
// of the pattern placed at coords (0, 0).
drawPattern(0, 0, 'no-repeat');
drawPattern(100, 0, 'repeat-x');
drawPattern(0, 100, 'repeat-y');
drawPattern(100, 100, 'repeat');
// Erase the fish image now that it's no longer needed.
ctx.clearRect(fishx - 1, fishy - 9, 25, 18);