Below is the code I'm currently using. When rotating, the 0
image scales properly to fill the canvas. (similarly background-size: cover
, except for using JavaScript on the canvas)
I am trying to add a rotation function with the following functions.
Maintain a centered image while rotating. I tried using width / 2
in translate
, and then vice versa in drawImage
, but as you can see, the image did not remain centered. I'm not sure if this is a conflict with my earlier x
and y
centering code, or if trigonometry is required here?
Automatically scale the image further to close the canvas. These are arbitrary rotations, not 90 degrees. I don’t want to crop the image more than I need to fill the corners of the canvas. This is a much more complex trigonometry than I'm used to dealing with.
I think this can be done with Math.sin
and Math.cos
, but it has been a very long time since I used them. I especially doubt how to reach No. 2. Any help would be greatly appreciated.
var canvas = document.querySelector('canvas')
var context = canvas.getContext('2d')
var image = new Image()
image.src = 'http://i.stack.imgur.com/7FsbT.jpg'
image.onload = function () {
var maxScaleX = canvas.width / image.width
var maxScaleY = canvas.height / image.height
scale = maxScaleX > maxScaleY ? maxScaleX : maxScaleY
var width = image.width * scale
var height = image.height * scale
var x = (width - canvas.width) / -2
var y = (height - canvas.height) / -2
var degrees = 30
context.setTransform(1, 0, 0, 1, 0, 0)
context.translate(width / 2, height / 2)
context.rotate(degrees * Math.PI / 180)
context.drawImage(image, x - width / 2, y - height / 2, width, height)
}
<canvas width="350" height="150" style="border: solid 1px black"></canvas>
Run code
source
share