Created
January 2, 2023 08:55
-
-
Save fre-sch/64a5ab5b2c505d13b42ca2f54d88dd03 to your computer and use it in GitHub Desktop.
Given a number of colors, calculate points on a circle centered on a canvas, draw lines between all points and then draw points over the lines using the colors.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const canvas = document.querySelector("#thecanvas") | |
const context = canvas.getContext("2d") | |
const midpoint = {x: canvas.width / 2, y: canvas.height / 2} | |
const colors = ["red", "green", "blue", "cyan", "magenta", "orange"] | |
const padding = 20 | |
const radius = (Math.min(canvas.width, canvas.height) - padding) / 2 | |
const d = Math.PI * 2 / colors.length | |
const points = colors.map((color, index) => { | |
const x = Math.cos(d * index) * radius | |
const y = Math.sin(d * index) * radius | |
return {color, x, y} | |
}) | |
const drawLines = (context, points) => { | |
context.strokeStyle = "black" | |
for (let i=0; i < points.length; ++i) { | |
for (let j=0; j < points.length; ++j) { | |
const p1 = points[i] | |
const p2 = points[j] | |
if (i == j) continue | |
context.beginPath() | |
context.moveTo( | |
midpoint.x + p1.x, | |
midpoint.y + p1.y) | |
context.lineTo( | |
midpoint.x + p2.x, | |
midpoint.y + p2.y) | |
context.stroke() | |
context.closePath() | |
} | |
} | |
} | |
const drawPoints = (context, points, pointRadius) => { | |
for (let i=0; i < points.length; ++i) { | |
context.beginPath() | |
context.fillStyle = points[i].color | |
context.arc( | |
midpoint.x + points[i].x, | |
midpoint.y + points[i].y, | |
pointRadius, 0, Math.PI*2, true) | |
context.fill() | |
context.closePath() | |
} | |
} | |
drawLines(context, points) | |
drawPoints(context, points, 10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment