Web/API/CanvasPattern/setTransform

From Get docs


The CanvasPattern.setTransform() method uses an SVGMatrix or DOMMatrix object as the pattern's transformation matrix and invokes it on the pattern.

Syntax

void pattern.setTransform(matrix);

Parameters

matrix
An SVGMatrix or DOMMatrix to use as the pattern's transformation matrix.

Examples

Using the setTransform method

This is just a simple code snippet which uses the setTransform method to create a CanvasPattern with the specified pattern transformation from an SVGMatrix. The pattern gets applied if you set it as the current fillStyle and gets drawn onto the canvas when using the fillRect() method, for example.

HTML

<canvas id="canvas"></canvas>
<svg id="svg1"></svg>

JavaScript

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var svg1 = document.getElementById('svg1');
var matrix = svg1.createSVGMatrix();

var img = new Image();
img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png';

img.onload = function() {
  var pattern = ctx.createPattern(img, 'repeat');
  pattern.setTransform(matrix.rotate(-45).scale(1.5));
  ctx.fillStyle = pattern;
  ctx.fillRect(0, 0, 400, 400);
};

Note that newer browser versions started to support DOMMatrix as an input to setTransform(), so for example you could replace the SVGMatrix in the above example with the following:

const matrix = new DOMMatrix([1, .2, .8, 1, 0, 0]);

Edit the code below and see your changes update live in the canvas:

Specifications

Specification Status Comment
HTML Living StandardThe definition of 'CanvasPattern.setTransform' in that specification. Living Standard

Browser compatibility

Update compatibility data on GitHub

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
setTransform Chrome

Full support 68

Edge

Full support 79

Firefox

Full support 33

IE

No support No

Opera

Full support 9

Safari

Full support 11.1

WebView Android

Full support 68

Chrome Android

Full support 68

Firefox Android

Full support 33

Opera Android

Full support 10.1

Safari iOS

Full support 11

Samsung Internet Android

Full support 10.0

DOMMatrix parameter supported Chrome

Full support Yes

Edge

Full support Yes

Firefox

Full support 79

IE

No support No

Opera

Full support Yes

Safari

Full support Yes

WebView Android

Full support Yes

Chrome Android

Full support Yes

Firefox Android

Full support 79

Opera Android

Full support Yes

Safari iOS

Full support Yes

Samsung Internet Android

Full support Yes

Legend

Full support  
Full support
No support  
No support


See also