JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas" width="500" height="500"></canvas>
JavaScript
var c = document.getElementById('canvas')
var ctx = c.getContext('2d')
function getRandomColor() {
var letters = '0123456789ABCDEF'
var color = '#'
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)]
}
return color
}
function drawPoly(p) {
var a = (Math.PI * 2) / p.s
ctx.beginPath()
ctx.translate(p.x, p.y)
ctx.moveTo(p.r, 0)
for (var i = 1; i < p.s; i++) {
ctx.lineTo(p.r * Math.cos(a * i), p.r * Math.sin(a * i))
}
ctx.fillStyle = p.co
ctx.strokeStyle = p.co
ctx.stroke()
ctx.fill()
ctx.translate(-p.x, -p.y)
ctx.closePath()
}
function pointInPolygon(xs, ys, x, y) {
var j = xs.length - 1
var oddNodes = false
for (var i=0; i<xs.length; i++) {
if ((ys[i] < y && ys[j] >= y ||
ys[j] < y && ys[i] >= y)
&& (xs[i] <= x || xs[j] <= x)) {
oddNodes ^= (xs[i] + (y - ys[i]) / (ys[j] - ys[i]) * (xs[j] - xs[i]) < x)
}
j=i
}
return oddNodes
}
function hitDetect(x, y, p) {
// generate x/ys for the shape
var xs = [p.x + p.r], ys = [p.y]
var a = (Math.PI * 2) / p.s
for (var i = 1; i < p.s; i++) {
xs.push(p.r * Math.cos(a * i) + p.x)
ys.push(p.r * Math.sin(a * i) + p.y)
}
return pointInPolygon(xs, ys, x, y)
}
var poly = {
s: 5,
x: 100,
y: 100,
r: 40,
co: '#ff0000'
}
drawPoly(poly)
c.addEventListener('click', function(event) {
var x = event.pageX - c.offsetLeft,
y = event.pageY - c.offsetTop
if(hitDetect(x, y, poly)){
poly.co = getRandomColor()
drawPoly(poly)
}
})