Last active
April 29, 2024 11:41
-
-
Save Zyndoras/6897abdf53adbedf02564808aaab94db to your computer and use it in GitHub Desktop.
Rotate base64 image (Javascript)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function rotate(srcBase64, degrees, callback) { | |
const canvas = document.createElement('canvas'); | |
const ctx = canvas.getContext('2d'); | |
const image = new Image(); | |
image.onload = function () { | |
canvas.width = degrees % 180 === 0 ? image.width : image.height; | |
canvas.height = degrees % 180 === 0 ? image.height : image.width; | |
ctx.translate(canvas.width / 2, canvas.height / 2); | |
ctx.rotate(degrees * Math.PI / 180); | |
ctx.drawImage(image, image.width / -2, image.height / -2); | |
callback(canvas.toDataURL()); | |
}; | |
image.src = srcBase64; | |
} | |
// Usage: | |
const img = document.getElementById('image'); | |
rotate(img.attributes.src.value, 90, function(resultBase64) { | |
img.setAttribute('src', resultBase64); | |
}); |
works like a charm!
thanks
nice! It solved my problem.
Here's an async version of this function that uses HTMLImageElement.decode()
This can be used to initiate loading of the image prior to attaching it to an element in the DOM (or adding it to the DOM as a new element), so that the image can be rendered immediately upon being added to the DOM. This, in turn, prevents the rendering of the next frame after adding the image to the DOM from causing a delay while the image loads.
Thank you!
I just needed these 2 lines:
canvas.width = degrees % 180 === 0 ? image.width : image.height;
canvas.height = degrees % 180 === 0 ? image.height : image.width;
thank you.
Thank you for this 👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks