简体   繁体   中英

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.

Again, entire Code is here.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM