/

HTML / CSS / JavaScript Tutorial

JavaScript canvas2d object method: setTransform()

[this page | pdf | back links]

The setTransform() method of the JavaScript DOM object returned by the getContext("2d") method applied to the HTML <canvas> element defines a transform matrix and then applies the transform() method.

 

It has the following syntax with the following parameters:

 

context.setTransform(x1,x2,x3,x4, x5, x6)

 

Parameter

Required / Optional

Description

x1

Required

Horizontal scaling

x2

Required

Horizontal skew

x3

Required

Vertical skew

x4

Required

Vertical scaling

x5

Required

Horizontal moving

x6

Required

Vertical moving

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head></head>
<body>
Transforms reset each time, using setTransform:<br>
<span id="element1"></span>
<br><br>
Transforms applied consecutively, using transform():<br>
<span id="element2"></span>

<script>
var x1 = document.createElement("CANVAS");
x1.setAttribute("width", "200");
x1.setAttribute("height", "100");
x1.setAttribute("style", "border: 1px solid black");
var c1 = x1.getContext("2d");
c1.strokeStyle = "blue";
c1.strokeRect(10, 10, 20, 10);
c1.setTransform(1, 0.4, -0.2, 1.3, 30, 15);
c1.strokeStyle = "red";
c1.strokeRect(10, 10, 20, 10);
c1.setTransform(1, 0.1, -0.2, 1.3, 30, 15);
c1.strokeStyle = "green";
c1.strokeRect(10, 10, 20, 10);
document.getElementById("element1").appendChild(x1);

var x2 = document.createElement("CANVAS");
x2.setAttribute("width", "200");
x2.setAttribute("height", "100");
x2.setAttribute("style", "border: 1px solid black");
var c2 = x2.getContext("2d");
c2.strokeStyle = "blue";
c2.strokeRect(10, 10, 20, 10);
c2.transform(1, 0.4, -0.2, 1.3, 30, 15);
c2.strokeStyle = "red";
c2.strokeRect(10, 10, 20, 10);
c2.transform(1, 0.1, -0.2, 1.3, 30, 15);
c2.strokeStyle = "green";
c2.strokeRect(10, 10, 20, 10);
document.getElementById("element2").appendChild(x2);
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodCanvas2dSetTransform() {
  var x = document.createElement("CANVAS"); var c = x.getContext("2d"); return !!c.setTransform;
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript DOM (and BOM)


Desktop view | Switch to Mobile