繁体   English   中英

画布:使用“画布”旋转图像

[英]Canvas: rotate image with 'canvas'

旋转图像并调整画布大小。

        var img = document.getElementById("i");
        width = img.width;
        height = img.height;

        canvasH.width = width;
        canvasH.height = height;
        ctxH.clearRect(0, 0, width, height);
        ctxH.save();
        ctxH.translate(width / 2, height / 2);
        ctxH.rotate(90 * Math.PI / 180);
        ctxH.translate(-(width / 2), -(height / 2));
        ctxH.drawImage(img, 0, 0);
        ctxH.restore();

        var w = canvasH.width;
// Resize canvas to meet rotated image size
// Comment last two lines and see how image rotated
        canvasH.width = height;
        canvasH.height = w;

画布已旋转(调整大小),但图像超出了可见区域。

如何获得旋转的图像?

内容: http : //jsfiddle.net/ouh5845c/1/

重要的是要知道更改画布的宽度/高度会隐式清除画布。 因此,与调整画布大小有关的所有操作,都必须渲染之前进行。

这是三角学上正确的方法,适用于任何角度:

        var img = document.getElementById("i"),
            angrad = angle * Math.PI /180,
            sin = Math.sin(angrad),
            cos = Math.cos(angrad);
        width = Math.abs(img.width*cos)+Math.abs(img.height*sin);
        height = Math.abs(img.height*cos)+Math.abs(img.width*sin);
        console.log(img.width,img.height,width,height);

        canvasH.width = width;
        canvasH.height = height;
        ctxH.clearRect(0, 0, width, height);
        ctxH.save();
        ctxH.translate(width / 2, height / 2);
        ctxH.rotate(angrad);
        ctxH.translate(-img.width / 2, -img.height / 2);
        ctxH.drawImage(img, 0, 0);
        ctxH.restore();

http://jsfiddle.net/ouh5845c/5/

==========================

以下故事你可能会忘记:

现在,由于需要旋转,因此旋转前后的宽度和高度的解释会有所不同。 (当然,对于角度不是90度的“多毛”情况,一些三角函数会派上用场)。

我相信这个小提琴可以满足您的需求:

        var img = document.getElementById("i");
        width = img.width;
        height = img.height;

        canvasH.width = height;
        canvasH.height = width;
        ctxH.clearRect(0, 0, width, height);
        ctxH.save();
        ctxH.translate(height / 2, width / 2);
        ctxH.rotate(90 * Math.PI / 180);
        ctxH.translate(-width / 2, -height / 2);
        ctxH.drawImage(img, 0, 0);
        ctxH.restore();

http://jsfiddle.net/ouh5845c/4/

如果您尝试将图像旋转90度,则应该可以。

var canvasH = document.getElementById("canvasH"),
        ctxH = canvasH.getContext("2d"),
        x = 0,
        y = 0,
        width = 0,
        height = 0,
        angle = 180,
        timeOut = null;

function loaded() {
        var img = document.getElementById("i");
        canvasH.width = img.height;
        canvasH.height = img.width;
        ctxH.clearRect(0, 0, img.width, img.height);
        ctxH.save();
        ctxH.translate(img.height, 0);
        ctxH.rotate(1.57079633);
        ctxH.drawImage(img, 0, 0);
        ctxH.restore();
}

jsFiddle

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM