六边形旋转 html5 canvas
Hexagone rotation html5 canvas
我想制作一个 class 来绘制六边形并旋转它,但我找不到在中心定义旋转点的方法。
谢谢。
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()
}
最后我发现:
// 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
我想制作一个 class 来绘制六边形并旋转它,但我找不到在中心定义旋转点的方法。 谢谢。
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()
}
最后我发现:
// 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