Answer the question
In order to leave comments, you need to log in
How can I rotate images in canvas?
How can I rotate images in canvas? There are 6 inputs, 3 of them we select a file, in 3 we select an angle for each and draw everything then drag it with the mouse.
I implemented everything except rotation, all links lead to rotating the entire slave area, but I need each img individually. Suggest a solution.
Answer the question
In order to leave comments, you need to log in
rotateAndCache = function(image, angle) {
var offscreenCanvas = document.createElement('canvas');
var offscreenCtx = offscreenCanvas.getContext('2d');
offscreenCanvas.width = image.height;
offscreenCanvas.height = image.width;
offscreenCtx.translate(offscreenCanvas.width / 2, offscreenCanvas.height / 2);
offscreenCtx.rotate(angle * Math.PI / 180);
offscreenCtx.drawImage(image, -(image.width / 2), -(image.height / 2));
return offscreenCanvas;
}
You need to rotate about some point. Do you want to rotate each image around its center? Some kind of corner?
In general, turning through angle a looks like
newX = obj.x * Math.cos(a) - obj.y * Math.sin(a);
newY = obj.x * Math.sin(a) + obj.y * Math.cos(a);
Lesson on transformations in canvas.
TL;DR : Imagine that the canvas is a landscape sheet. A piece of a landscape sheet cannot be rotated, you can only rotate the entire sheet. But you can remember that you turned the sheet and then turn it in the opposite direction. Same with canvas:
ctx.save(); // запомнили текущее состояние канваса
ctx.rotate(rad); // повернули канвас целиком
// рисуем, заливаем и вообще делаем что хотим с повёрнутым канвасом
ctx.restore(); // восстанавливаем состояние, которое запомнили ранее (читай повернули листик назад как было)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question