B
B
bro-dev2016-04-14 15:24:13
JavaScript
bro-dev, 2016-04-14 15:24:13

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

3 answer(s)
B
bro-dev, 2016-04-14
@xPomaHx

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;
        }

I found a solution, put into the function what you need to rotate the img or canvas, write the angle and return the rotated canvas. which we can shove into the main one anywhere.

N
Niomin, 2016-04-14
@Niomin

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);

In this case, obj.x and obj.y are coordinates relative to the center of rotation. In your case, as I understand it, for each picture they need to be set separately before rotation.

G
GreatRash, 2016-04-14
@GreatRash

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 question

Ask a Question

731 491 924 answers to any question