Cobar
Cobar

Reputation: 1

Drawing shapes around in a circle

I'm relatively new to Canvas and I'm wondering how could I rotate(and draw) squares around in circle. Right now, I am starting with 5 squares and want to have them 150 from the center. As it stands, I have this:

let context = document.getElementById("drawingSurface");
ctx = context.getContext('2d');

let numberOfSquares = 5;
let radius = 150;
let angles = 360 / numberOfSquares;
let toRadians = angles * Math.PI/180;

for(let i = 0; i<= numberOfSquares;i++){
  ctx.save();
  ctx.translate(200,200);
  ctx.rotate(toRadians);
  ctx.fillRect(0,radius,20,20);
  ctx.restore();
  toRadians += toRadians;
}

However, the squares are not uniform and I am having trouble making them as such. How would I attain this?

Upvotes: 0

Views: 1240

Answers (1)

Blindman67
Blindman67

Reputation: 54026

Using trig functions to find a point at angle.

Rather than use the transformation matrix to get the box positions use trig functions sin and cos.

To get a position at an angle (ang is in radians)

var x = Math.cos(ang) * distance;
var y = Math.sin(ang) * distance;

To get a position at an angle from a point px,py

var x = Math.cos(ang) * distance + px;
var y = Math.sin(ang) * distance + py;

An example in code below

var canvas = document.createElement("canvas");
canvas.width = innerWidth - 40;
canvas.height = innerHeight - 40;
var ctx = canvas.getContext("2d");
document.body.appendChild(canvas);


function drawCircle(x,y,radius,fillC,strokeC,lineW){
    ctx.fillStyle = fillC;
    ctx.strokeStyle = strokeC;
    ctx.lineWidth = isNaN(lineW) ? ctx.lineWidth : lineW;
    ctx.beginPath();
    ctx.arc(x, y, radius, 0, Math.PI * 2);
    if(fillC !== null && fillC !== undefined){
        ctx.fill();
    }
    if(strokeC !== null && strokeC !== undefined){
        ctx.stroke();
    }
}
function drawSquare(x,y,size,fillC,strokeC,lineW){
    ctx.fillStyle = fillC;
    ctx.strokeStyle = strokeC;
    ctx.lineWidth = isNaN(lineW) ? ctx.lineWidth : lineW;
    ctx.beginPath();
    ctx.rect(x - size / 2, y - size / 2, size, size);
    if(fillC !== null && fillC !== undefined){
        ctx.fill();
    }
    if(strokeC !== null && strokeC !== undefined){
        ctx.stroke();
    }
}

const startAngle = Math.PI * -0.5;
const boxSize = Math.min(canvas.width,canvas.height) / 8;
const circleX = canvas.width / 2;
const circleY = canvas.height / 2;
const radius = Math.min(canvas.height,canvas.width) /2 - boxSize /2 - 4;
const colors = ["red", "blue", "blue", "blue", "blue", "blue", "blue", "blue"];
const boxCount = colors.length;
ctx.lineJoin = "round";


drawCircle(circleX,circleY,radius,"black");
for(var i = 0; i < boxCount; i++){
    var ang = i * ((Math.PI * 2) / boxCount) + startAngle;
    var x = Math.cos(ang) * radius + circleX;
    var y = Math.sin(ang) * radius + circleY;
    drawSquare(x, y, boxSize, colors[i], "white", 3);
}

Upvotes: 3

Related Questions