How can I rotate the image on the canvas and expand the parent so that the image is not cut off?

How to rotate an image on HTML5 canvas without losing image data? What I mean is that if the rotation causes the image to grow larger, I want to also expand the Canvas container so that the image is not cut off. The following image might say better: enter image description here

The brown is actually the container that wraps the canvas. I want to expand it (and the Canvas to fit the image) when the Canvas is rotated so that the image isn't cut off.

Update: The image can be larger than the Canvas, so I use the bounding box method to compute the proportional dimensions with the parent container to fit the image. Therefore, the Canvas dimensions style

will be calculated, while the height and width attributes will be the image dimensions.

Any help is appreciated!

+3


source to share


1 answer


This feature will resize your canvas to fit exactly the rotated image. You must specify the width and height of the image, and the current rotation angle is in degrees.

[Edited: OOPS! I had to convert angle to radians ... And ... should change canvas width / height , not css width / height]



function resizeCanvasContainer(w,h,a){
var newWidth,newHeight;
  var rads=a*Math.PI/180;
  var c = Math.cos(rads);
  var s = Math.sin(rads);

    if (s < 0) { s = -s; }
    if (c < 0) { c = -c; }
    newWidth = h * s + w * c;
    newHeight = h * c + w * s ;

var canvas = document.getElementById('canvas');
canvas.width = newWidth + 'px';
canvas.height = newHeight + 'px';
}

      

+4


source







All Articles