Answer the question
In order to leave comments, you need to log in
How to arrange elements in canvas in a circle?
I'm just starting to understand canvas , and I'm trying to achieve this effect:
To do this, I draw the same picture 6 times in the canvas at the coordinates corresponding to the circle's trajectory.
At the moment, I don’t understand how to rotate each rendered element by a certain number of degrees.
code pen
let canvas = document.querySelector('canvas'), //берем канвас
ctx = canvas.getContext('2d'), // указываем контекст
img = new Image(), // создаем картинку-елемент, которая потом будет отрисована в канвас
baseX = (window.innerWidth/100)*50, // центр канваса по высоте
baseY = (window.innerHeight/100)*50, // центр канваса по ширине
r = baseX/4; //радиус круга по которому будут выстроины елементы
canvas.height=window.innerHeight; //Ростягиваем канвас на весь экран
canvas.width=window.innerWidth;
ctx.beginPath(); //Отрисовываем вспомогательный круг ,что бы было видно размеры и траэкторию
ctx.arc(baseX, baseY, r, 0, 2 * Math.PI); //Где центр круга находиться по центру канваса , радиус равный r
ctx.stroke(); //Зарисовываем круг
img.onload=function(){ //когда картинка загрузиться
let angle=0; //начальное значение угла наклона елементов
for(let i=0; i<6; i++){ // рисуем 6 раз елемент из картинки
let ctx = canvas.getContext('2d');
let elem = ctx.drawImage(img, getPos(angle).x , +getPos(angle).y); //тут getPos() дает координаты по траэктории круга
angle-=60; //угол уменьшается на 60 градусов для каждого елемента (360/6=60)
}
}
img.src="https://dev.thesociety.site/wefwfwefwewfdss/vr.svg"; //картинка источник
function getPos(angle){
let vx=baseX+Math.sin(-angle*Math.PI/180)*r;
let vy=baseY+Math.cos(-angle*Math.PI/180)*r;
console.log(vx.toFixed(2),vy.toFixed(2));
return {
x: (vx).toFixed(2),
y: (vy).toFixed(2)
};
}
.rotate( )
, but I couldn't rotate the elements - only the whole canvas
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question