Andrea_86
Andrea_86

Reputation: 527

Canvas Rotation+Scaling

I need to rotate an image in a canvas and simultaneously resize it to make sure that the corners of the canvas does not remain empty. The solution should be something similar to what do aviary in the "Crop, Resize & Rotate" example.

I think the solution is to combine the functions of rotation and resize of canvas, but I can not find any concrete solution to the problem and I didn't find any exaustive example on the web.

Any advice would be helpful

Thanks

Upvotes: 4

Views: 302

Answers (2)

Blindman67
Blindman67

Reputation: 54026

I have not had a look at the example you have given but I gave a detailed answer on the problem of fitting a rotated image onto a canvas so that there is no blank spaces.

There is some math involved (go figure) but it is just basic trigonometry and I provided an explanation of how its all done. There are two solutions, one that finds the min scale that will fit the canvas for any rotation and the other the will find the min scale to fit the canvas for a particular rotation.

It is assumed that the image is centered, if not there is an easy way to adapt the code provided by supplying an abstract canvas size so that the rotated image is centered on that abstract canvas.

So if your center of image is at x = 100, y = 100 and the canvas is canvasWidth = 300, canvasHeight = 300 then just use an abstract size of absCanvasWidth = (canvasWidth - x) * 2; and then the image at x = absCanvasWidth/2 do the same for height. That will fit the rotated, translated image to fill the canvas.

The answer with the code can be found for the question After rotate, draw Image at correct position

Upvotes: 2

rphv
rphv

Reputation: 5537

Here's some code that might help you. This shows how to rotate an image 90 degrees clockwise, then scale it to fit in the original canvas space.

window.onload = function() {
  var img = document.getElementById("myImage");
  var rotatedCanvas = document.getElementById("myRotatedCanvas");
  var width = rotatedCanvas.offsetWidth;
  var height = rotatedCanvas.offsetHeight;

  // draw the original image 
  var ctx = document.getElementById("myCanvas").getContext("2d");
  ctx.drawImage(img, 0, 0);

  // draw the rotated image
  ctx = rotatedCanvas.getContext("2d");
  ctx.rotate(90 * Math.PI / 180);
  // the last two parameters scale the image
  ctx.drawImage(img, 0, -width, height, width);
};
img {
  display: none;
}
canvas {
  border: 1px black solid;
}
<img src="http://imgur.com/UeMOrix.gif" id="myImage"/>
<canvas id="myCanvas" width="400" height="150"></canvas>
<br>
<canvas id="myRotatedCanvas" width="400" height="150"></canvas>

Upvotes: 0

Related Questions