簡體   English   中英

使用畫布上下文旋轉圖像

[英]Rotating an image with canvas context

我有這個代碼

Allocate.prototype.Rotate = function () {
var canvas = document.getElementById("underCanvas");
var context = canvas.getContext("2d");
canvas.width = canvas.width;
context.lineWidth = "1";
context.save();
context.translate(this.drawStart.x + this.img.width * 0.5,
              this.drawStart.y + this.img.height * 0.5);
context.rotate(Math.Pi/2);
context.translate(-(this.drawStart.x + this.img.width * 0.5),
              -(this.drawStart.y + this.img.height * 0.5));
context.drawImage(this.img, this.drawStart.x, this.drawStart.y, this.drawStart.w, this.drawStart.h, this.drawStart.x, this.drawStart.y, this.drawStart.w, this.drawStart.h);

context.rect(this.drawStart.x, this.drawStart.y, this.drawStart.w, this.drawStart.h);
context.stroke();
context.restore();
}

我認為這種類分配方法應該做的是-在(this.img)內部繪制圖像(this.img)旋轉90度。 結果:繪制了一個變換后的矩形,但圖像仍未旋轉。 為什么?

誰能幫我實現這一目標?

此代碼是類分配的一部分。 我正在做sorta網絡繪畫,並且希望能夠旋轉分配的區域。 謝謝。

如果要按圖像中心旋轉圖像,則需要在旋轉之前進行平移(根據需要進行調整):

/// first translate
context.translate(this.drawStart.x + this.img.width * 0.5,
                  this.drawStart.y + this.img.height * 0.5);

/// then rotate
context.rotate(0.5 * Math.PI);  /// 90 degrees

/// then translate back
context.translate(-(this.drawStart.x + this.img.width * 0.5),
                  -(this.drawStart.y + this.img.height * 0.5));

/// draw image

它無法正常工作的原因可能有多種:

  • 圖像是否正確加載(即,用於使圖像在繪制時可用的onload處理程序)
  • 這些屬性包含哪些值並且它們是有效的(即,未定義等)。

為了使旋轉生效,您需要選擇旋轉點或樞軸。 樞軸通常是圖像的中心,它是通過使用其一半的寬度和高度獲得的。

由於旋轉始終以坐標系的原點(0,0)旋轉,因此您首先需要將此原點平移到圖像中心所在的位置。

然后旋轉,以正確繪制圖像,您需要在旋轉后向后平移,否則圖像的角將在中心,因為圖像總是從左上方繪制。

當然必須使用相同的變換繪制矩形。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM