[英]Rotate Custom Canvas Object around its own center
I created some Functions, these will draw Rectangles, Circles, Hexagons etc. One of them looks like this: 我创建了一些函数,这些函数将绘制矩形,圆形,六边形等。其中一个看起来像这样:
rotation = 0;
function hex(hex_sides, hex_size, hex_color){
x = ctx.canvas.width/2;
y = ctx.canvas.height/2;
ctx.save();
ctx.translate(x,y);
ctx.rotate(rotation*Math.PI/180);
//ctx.moveTo(x + hex_size * Math.cos(0), y + hex_size * Math.sin(0));
ctx.moveTo(0,0);
for (i = 0; i < hex_sides+1; i++) {
ctx.lineTo(x + hex_size * Math.cos(i * 2 * Math.PI / hex_sides), y + hex_size * Math.sin(i * 2 * Math.PI / hex_sides));
}
ctx.strokeStyle = hex_color;
ctx.stroke();
ctx.restore();
}
Now i call the Functions to Draw the Shapes inside my animation loop. 现在,我在动画循环中调用“绘制形状的函数”。
function loop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
circle(200);
circle(220);
hex(6, 180, "#fff");
rotation += 0.4;
requestAnimationFrame(loop);
}
The Issue here is that i can NOT get the Custom Shape (Hexagon) to rotate around the center (its own axis). 这里的问题是我无法使“自定义形状”(六边形)围绕中心(其自身的轴)旋转。 I have figured out it has something to do with the
translate()
and the for loop where the lines are drawn. 我已经弄清楚它与
translate()
和绘制线条的for循环有关。
Nevermind... figured it out, i have forgotten to substract half of the shapes width from the translation point and also the order seems to be more important then i tought. 没关系...弄清楚了,我忘了从平移点减去形状宽度的一半,而且顺序似乎比我更重要。
Working Code 工作守则
function hex(hex_sides, hex_size, hex_color){
x = ctx.canvas.width/2;
y = ctx.canvas.height/2;
ctx.save();
ctx.translate(x,y);
ctx.rotate(rotation*Math.PI/180);
//ctx.moveTo(x + hex_size * Math.cos(0), y + hex_size * Math.sin(0));
ctx.moveTo(0,0);
for (i = 0; i < hex_sides+1; i++) {
ctx.lineTo(x/hex_size + hex_size * Math.cos(i * 2 * Math.PI / hex_sides), y/hex_size + hex_size * Math.sin(i * 2 * Math.PI / hex_sides));
}
ctx.strokeStyle = hex_color;
ctx.stroke();
ctx.restore();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.