2013-12-17 114 views
0

图像我有这样的代码旋转用帆布背景

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

什么,我觉得这个类的方法分配应该做的 - 是画由rectange内90度旋转图像(this.img)。什么出来:它绘制一个变换的矩形,但图像仍然不旋转。为什么?

任何人都可以帮助我做到这一点吗?

此代码是类分配的一部分。我正在做一个网络绘画,并希望能够旋转分配的区域。谢谢。

回答

1

你需要旋转前翻译,如果你想通过其中心旋转图像(根据需要进行调整):

/// 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 

原因为它不行可以是几种:

  • 图像是否正确加载(即,是用于使图像在绘制时可用的加载处理程序)
  • 这些属性包含哪些值并且它们是否有效(即,未定义等)

为了旋转工作,您需要选择旋转点或旋转点。枢轴通常是通过使用其半宽和高度获得的图像的中心。

由于旋转始终在坐标系的原点(0,0)上旋转,所以首先需要将该原点转换为图像中心所在的位置。

然后旋转,为了正确地绘制图像,需要在旋转之后回转,否则图像的角落将位于中心,因为图像总是从左上角绘制。

矩形必须绘制与当然应用相同的转换。

+0

rect里面的图像现在消失了。我认为它与我的drawImage-8参数绘图方式有关。试图改变它 –

+0

@AlexanderCapone是的,你也需要调整。我只是在这里显示基本原则:-) – K3N

+0

我编辑了有问题的代码。 你能解释为什么它不工作?因为我无法理解,没有任何东西在旋转! –