2015-06-01 107 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