Here I'm going to post whatever that is interesting for me. All things about programming using JavaScript and ASP.NET Core. And something else.

A blog about ASP.Net Core and JavaScript

There are a lot of tutorials, which describe how to perform canvas elements transformations. For example, there is a cool article in the MDN web docs.

But when I tried to create a common function to manipulate the canvas objects, it took a couple of hours to understand how to perform transformations correctly for every canvas object.


The draw() function

The rule of thumb you have to use when dealing with canvas transformations is the right transformation order: translate(), rotate(), scale(). It is the most common order until you want some distortion effects. 

So, the main drawing function could look like this:

function draw(ctx, rect) {; ctx.translate(rect.origin.x, rect.origin.y); ctx.rotate(rect.angle * Math.PI / 180); ctx.scale(rect.scaleX, rect.scaleY); ctx.fillRect(0, 0, rect.width, rect.height); ctx.restore(); };

Here ctx is the reference to the canvas 2d context, and the rect is the plain javascript object which configures rectangle properties. Example of the such object:

  width: 60,
  height: 40,
  movable: false,
  angle: 30,
  scaleX: 2,
  scaleY: 2,
  origin: {
    x: 120,
    y: 20

The origin property contains the object, which configures the x and the y coordinates of the point you will rotate your rectangle around. It is the primary point for the scaling, and it is the point from which you start rectangle drawing.

As you can see, to rotate and scale rectangle you have to change the angle, scaleX and (or) scaleY properties of the rectangle configuration object. To move the rectangle, you have to change the x and (or) y properties of the origin object.

You can investigate the complete example which shows how you can rotate and scale canvas rectangles, and how you can move one of them using the mouse events. This example available in the ctxtransforms Github repository.