【问题标题】:HTML5 canvas image rotate left rotate rightHTML5画布图像向左旋转向右旋转
【发布时间】:2012-10-18 16:17:17
【问题描述】:

我已经在画布中绘制了一张图片。

现在我正在尝试的是,如果用户单击向左旋转按钮,总画布应该向左旋转(即图像旋转到 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);

还有一个疑问,我们不能旋转整个画布以保持图像的正确纵横比

【问题讨论】:

    标签: html html5-canvas


    【解决方案1】:

    这是简单的代码,

    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 度。

    【讨论】:

    • 我是这样实现的,但没有运气。而不是旋转总图像正在消失。有问题的代码已更新。
    • 很抱歉仍然遇到同样的问题。图像消失。
    • 尝试不使用 ctx.translate(-translateX,-translateY);
    • 好的。@Eonasdan。谢谢你的建议! :)
    • 非常感谢 MJQ。你救了我很多头痛。添加行后 ctx.save(); & ctx.restore();它奏效了。
    【解决方案2】:

    正如我在网上验证的那样,它比我们在上述过程中所做的要简单得多。

    这是我在我的博客HTML5 canvas image rotation发布的链接

    【讨论】:

      猜你喜欢
      • 2011-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-05
      • 1970-01-01
      • 2015-10-01
      • 1970-01-01
      • 2023-04-10
      相关资源
      最近更新 更多