我在画布上画了一幅画。
现在我正在尝试的是,如果用户点击roate left按钮,整个画布应该向左旋转(即图像旋转到90度),如果旋转右画布应该向右旋转。
这就是我尝试的旋转。请告诉我实现这个目标的代码

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

工作溶液:
// 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);

还有一个疑问,我们不能旋转整个画布以保持图像的适当长宽比

最佳答案

这是简单的代码,

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

其中r可以是1到36,旋转10到360度。

09-25 16:52
查看更多