簡體   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