HTML5 canvas image rotate left rotate right

放肆的年华 提交于 2020-01-04 11:49:51

问题


I have drawn an image into canvas.

Now what i am trying is if user click on roate left button total canvas should rotate left (i.e., Image rotate to 90 degress) and if rotate right canvas should rotate right.

this is what i tried for rotation. Please suggest me the code to achieve this

var canvasId = document.getElementById("preview");
var cntxt = canvasId.getContext("2d");
cntxt.translate($("#preview").width()-1, $("#preview").height()-1);
cntxt.rotate(convertToRadians(90));
cntxt.drawImage(canvasId, 0, 0, $("#preview").width(), $("#preview").height());

function convertToRadians(degree) {
    return degree*(Math.PI/180);
}

Working Solution:

// Getting the canvas
var canvasId = document.getElementById(id);
var ctx = canvasId.getContext("2d");

// Store the current transformation matrix
ctx.save();

ctx.setTransform(1,0,0,1,0,0);

// Getting the canvas width and height
var w = $("#preview").width();
var h = $("#preview").height();

ctx.clearRect(0, 0, w, h);

// Restore the transform
ctx.restore();

// TranslateX should be canvaswidth/2 and translateY should be canvasheight/2
var translateX = w/2;
var translateY = h/2;

// translating the context
ctx.translate(translateX,translateY);

// As we need to rotate the image to 90 degrees
// Where r can be 1 to 36 for 10 to 360 degree rotation
var r = 9;
ctx.rotate(r*10*Math.PI/180);
ctx.translate(-translateX,-translateY);

// Drawing canvas
ctx.drawImage(ImageObject, 0, 0, w, h);

One more doubt can't we rotate the whole canvas to keep the proper aspect ratio of the image


回答1:


Here is the simple code for that,

var canvasId = document.getElementById("preview");
var ctx = canvasId.getContext("2d");
ctx.setTransform(1,0,0,1,0,0);
ctx.clearRect(0, 0, $("#preview").width(), $("#preview").height());
var translateX = ($("#preview").width())/2;
var translateY = ($("#preview").height())/2;
ctx.translate(translateX,translateY);
var r = 9;
ctx.rotate(r*10*Math.PI/180);
ctx.translate(-translateX,-translateY);
ctx.drawImage(imgsrc, 0, 0, $("#preview").width(), $("#preview").height());

Where r can be 1 to 36 for 10 to 360 degree rotation.




回答2:


As i verified in the net it is lot simpler than what we did in the above process.

So here is the link which i have posted in my blog HTML5 canvas image rotation



来源:https://stackoverflow.com/questions/12912818/html5-canvas-image-rotate-left-rotate-right

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!