Как повернуть вокруг своей оси объект в canvas?

Рейтинг: 0Ответов: 0Опубликовано: 14.01.2023

Объект - шестиугольник ( hexagon ), я абсолютно не пойму как его повернуть именно вокруг своей оси, он поворачивается, но я даже не пойму вокруг какой точки он поворачивается ( похоже, даже не вокруг точки с координатами x,y, откуда начинается сама фигура ).
Установить translate чтобы точка вращения была в середине не особо работает. Туториалы показывают только для квадратов такое, но попытки подстроить под шестиугольник не помогают:(

https://codepen.io/Niksak0v/pen/JjByPrK

draw(){
    ctx.beginPath();
    ctx.fillStyle = this.color;
    for (var i = 0; i < 6; i++){
        ctx.lineTo(this.x + this.size * Math.cos(this.a * i), this.y + this.size * Math.sin(this.a * i));
    }
    ctx.closePath();
    ctx.fill()
}

Собственно сам код по ссылке, сверху часть где рисуется сам хексагон, вот в этой части я и шаманил с его поворотами

//Определение холста
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
//Размеры холста
const width = canvas.width = window.innerWidth;
const height = canvas.height = window.innerHeight;
//Рандомное число между min и max
function random(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

function randomRGB() {

  return `rgb(${random(0, 255)},${random(0, 255)},${random(0, 255)})`;
}



//Определение хексагона
class Hexagon {
  //Свойства мяча
  constructor(x, y, velX, velY, color, size) {
    this.x = x;
    this.y = y;
    this.velX = velX;
    this.velY = velY;
    this.color = color;
    this.size = size;
    this.a = 2 * Math.PI / 6;
  }



  //Функции хексагона
  draw() {
    ctx.beginPath();
    ctx.fillStyle = this.color;
    for (var i = 0; i < 6; i++) {
      ctx.lineTo(this.x + this.size * Math.cos(this.a * i), this.y + this.size * Math.sin(this.a * i));
    }
    ctx.closePath();
    ctx.fill()
  }

  //Движение хексагона
  update() {
    //Чтоб не провалился вправо
    if ((this.x + this.size) >= width) {
      this.velX = -(Math.abs(this.velX));
    }

    if ((this.x - this.size) <= 0) {
      this.velX = Math.abs(this.velX);
    }

    if ((this.y + this.size) >= height) {
      this.velY = -(Math.abs(this.velY));
    }

    if ((this.y - this.size) <= 0) {
      this.velY = Math.abs(this.velY);
    }

    this.x += this.velX;
    this.y += this.velY;
  }

}

var hexs = [];

while (hexs.length < 5) {
  const size = random(50, 70)
  const hex = new Hexagon(
    random(0 + size, width - size),
    random(0 + size, height - size),
    random(5, 10),
    random(5, 10),
    randomRGB(),
    size
  );

  hexs.push(hex);
}

function loop() {
  ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
  ctx.fillRect(0, 0, width, height);

  for (hex of hexs) {
    hex.draw();
    hex.update();
  }

  requestAnimationFrame(loop);
}

loop();
html {
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
  height: 100%;
  margin: 0;
}

body {
  overflow: hidden;
  height: inherit;
  margin: 0;
}
<canvas></canvas>

Ответы

Ответов пока нет.