It is a simple code trying to change the color of a polygon in javascript
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var polygon = [
[100, 100],
[100, 200],
[200, 200],
[200, 100]
];
// Draw the polygon
ctx.fillStyle = "black";
ctx.beginPath();
ctx.moveTo(polygon[0][0], polygon[0][1]);
for (var i = 1; i < polygon.length; i++) {
ctx.lineTo(polygon[i][0], polygon[i][1]);
}
ctx.closePath();
ctx.fill();
// Add event listener to change the color of the polygon when clicked
canvas.addEventListener("click", function(event) {
var x = event.pageX - canvas.offsetLeft;
var y = event.pageY - canvas.offsetTop;
ctx.beginPath();
ctx.moveTo(polygon[0][0], polygon[0][1]);
for (var i = 1; i < polygon.length; i++) {
ctx.lineTo(polygon[i][0], polygon[i][1]);
}
ctx.closePath();
if (ctx.isPointInPath(x, y)) {
if (ctx.fillStyle == "black") {
ctx.fillStyle = "red";
} else {
ctx.fillStyle = "pink";
}
ctx.fill();
}
});
<canvas id="myCanvas" width="400" height="400"></canvas>
It changes the color to pink on first click. It does not matter if instead of Color Names I use Hex Values or RGB (Red; #FF0000; rgb(255,0,0))