The HTML5 canvas API can define a custom transformation matrix that can be applied to the current context.
The following code creates a translational transform via the transform() method.
<html> <head> <script> window.onload = function(){ let canvas = document.getElementById("myCanvas"); let context = canvas.getContext("2d"); /* w ww . j a va2 s . c om*/ let rectWidth = 150; let rectHeight = 75; // translation matrix: // 1 0 tx // 0 1 ty // 0 0 1 let tx = canvas.width / 2; let ty = canvas.height / 2; // apply custom transform context.transform(1, 0, 0, 1, tx, ty); context.fillStyle = "blue"; context.fillRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight); }; </script> </head> <body> <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;"> </canvas> </body> </html>
The code above created a custom translation transform via translation transformation matrix.
A transformation matrix is a 2-dimensional matrix.
It can be used to transform the current matrix.
The custom transformations can be applied to the context state using the transform():
context.transform(a,b,c,d,e,f);