2015-06-01 109 views
0

我正在寻找一个类来绘制六边形并旋转它,但我没有找到方法来定义中心上的旋转点。 谢谢。Hexagone旋转html5画布

function Hexagone (sides, size, centerX, centerY, rotation) { 
    this.sides = sides 
    this.size = size 
    this.centerX = centerX 
    this.centerY = centerY 
    this.rotation = rotation || 0 
} 

Hexagone.prototype.draw = function() { 
    ctx.beginPath() 
    // Reset transformation matrix 
    ctx.setTransform(1, 0, 0, 1, 0, 0); 
    ctx.translate(this.centerX, this.centerY) 
    ctx.rotate(this.rotation * Math.PI/180) 
    ctx.moveTo(this.centerX + this.size * Math.cos(0), this.centerY + this.size * Math.sin(0)) 
    for (var i = 0; i <= this.sides; i++) { 
    ctx.lineTo(this.centerX + this.size * Math.cos(i * 2 * Math.PI/this.sides), this.centerY + this.size * Math.sin(i * 2 * Math.PI/this.sides)) 
    } 

    //temp style 
    ctx.strokeStyle = "#000000" 
    ctx.lineWidth = 2 
    ctx.stroke() 
} 
+1

非常正确......很高兴你能解决它!您应该发布您的答案(并在以后接受它),以便您的问题脱离“未答复”列表。 ;-) – markE

+0

链接笔似乎是空的 – K3N

回答

0

最后我发现:

// Reset transformation matrix 
ctx.setTransform(1, 0, 0, 1, 0, 0) 
// We need to translate before 
ctx.translate(this.centerX, this.centerY) 
ctx.rotate(this.rotation * Math.PI/180) 
// And after 
ctx.translate(-this.centerX, -this.centerY) 
// Don't forget to reset the matrix on the beginning. 

您可以检查codepen完整的代码。 http://codepen.io/anon/pen/bdgJWo