Rotate Existing Image on Canvas

I’m attempting to rotate an image that has already been drawn on a HTML canvas, like so:

var canvas = document.getElementById("editorCanvas");
var ctx = canvas.getContext("2d");

var canvasOffset = $("#editorCanvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;

var startX;
var startY;
var isDown = false;


var pi2 = Math.PI * 2;
var resizerRadius = 4;
var rr = resizerRadius * resizerRadius;
var draggingResizer = {
    x: 0,
    y: 0
};
var imageX = 0;
var imageY;
var imageWidth, imageHeight, imageRight, imageBottom;
var draggingImage = false;
var startX;
var startY;

var img = new Image();
img.crossOrigin='anonymous';
img.onload = function () {
    var ratio = img.width / img.height;

    imageWidth = 71;
    imageHeight = imageWidth / ratio;
    imageY = (245-imageHeight)/2;
    if (imageHeight > 245) {
        imageHeight = 245;
        imageWidth = imageHeight * ratio;
        imageY = 0;
    }

    imageX = ((canvas.width-imageWidth)/2);
    imageY = ((canvas.height-imageHeight)/2);

    imageRight = imageX + imageWidth;
    imageBottom = imageY + imageHeight;

    draw(true, false);
}

function draw(withAnchors, withBorders) {

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    ctx.drawImage(img, 0, 0, img.width, img.height, imageX, imageY, imageWidth, imageHeight);

    if (withAnchors) {
        drawDragAnchor(imageX, imageY);
        drawDragAnchor(imageRight, imageY);
        drawDragAnchor(imageRight, imageBottom);
        drawDragAnchor(imageX, imageBottom);
    }

    if (withBorders) {
        ctx.beginPath();
        ctx.moveTo(imageX, imageY);
        ctx.lineTo(imageRight, imageY);
        ctx.lineTo(imageRight, imageBottom);
        ctx.lineTo(imageX, imageBottom);
        ctx.closePath();
        ctx.stroke();
    }

}

I was hoping it was this simple:

    function rotateImage() {
        var rotateCanvas = document.getElementById('editorCanvas');
        var rotateContext = canvas.getContext('2d');
        rotateContext.rotate(90 * Math.PI / 180);
    }

But I think the only way is through redrawing the image?

Is there any way of rotating an image on a canvas without redrawing it, if not how would I go about rotating an image on a canvas?


Source: html5

Leave a Reply