If you're looking to perform a custom transformation other than a translation, scale, or rotation, the HTML5 canvas API also provides a method which allows us to define a custom transformation matrix that can be applied to the current context. In this recipe, we'll manually create a translational transform to demonstrate how the transform()
method works.
Follow these steps to perform a custom transform:
Define the canvas context and the dimensions for our rectangle:
window.onload = function(){ var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); var rectWidth = 150; var rectHeight = 75;
Apply a custom transform by manually translating the canvas context:
// translation matrix: // 1 0 tx // 0 1 ty // 0 0 1 var tx = canvas.width / 2; var ty = canvas.height / 2; // apply custom transform context.transform(1, 0, 0, 1, tx, ty);
Draw the rectangle...