Patterns E-mail

pattern = context.createPattern (image, repetition);

  • Returns a pattern object that uses image to generate a repeating pattern in the direction given by repetition.
  • image must be an img object, a canvas object or a video element, but not an imagedata object.
  • repetition must be 'repeat', 'repeat-x', 'repeat-y' or 'no_repeat'.
  • repetition values 'repeat-x' and 'repeat-y' are rendered incorrectly as 'repeat' in Firefox.
  • If no value is specified for repetition then 'repeat' will be used as the default.
  • Throws TYPE_MISMATCH_ERR if image is not an img object, a canvas object or a video element.
  • Throws INVALID_STATE_ERR if image contains no image data.
  • Throws SYNTAX_ERR if repetition is not a valid value.
  • Returns NULL while processing.

Unfortunately, your browser does not support modern web standards.
Please use one of the supported browsers listed below, they're free to download and use.

Supported browsers: Firefox, Safari, Chrome, Opera, and Konqueror.


Source (click to expand)

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);