JSFiddle - React, Tailwind, and code Playground
by PiereDome
HTML
<canvas id='canvas'></canvas>
CSS
canvas{
position: absolute;
top: 10px;
left: 10px;
box-shadow: 0px 4px 15px #AAAAAA;
}
JavaScript
var Shape = function(x, y, verx, very, fill) {
this.x = x || 0;
this.y = y || 0;
var vertx = verx || [0, 10, 10, 0, 0];
var verty = very || [0, 0, 10, 10, 0];
var nvert = vertx.length;
this.fill = fill || '#AAAAAA';
this.selectedPoint = null;
this.draw = function(ctx) {
ctx.fillStyle = this.fill;
ctx.beginPath();
ctx.moveTo(vertx[0] + this.x, verty[0] + this.y);
for (var i = 1; i < nvert; i++) {
ctx.lineTo(vertx[i] + this.x, verty[i] + this.y);
}
ctx.strokeStyle = '#000000';
ctx.lineWidth = 1;
ctx.stroke();
ctx.fill();
};
this.outline = function(ctx, color, width) {
ctx.fillStyle = this.fill;
ctx.strokeStyle = color;
ctx.lineWidth = width;
ctx.beginPath();
ctx.moveTo(vertx[0] + this.x, verty[0] + this.y);
for (var i = 1; i < nvert; i++) {
ctx.lineTo(vertx[i] + this.x, verty[i] + this.y);
}
ctx.stroke();
for (var i = 0; i < nvert; i++) {
ctx.beginPath();
ctx.arc(vertx[i] + this.x, verty[i] + this.y, 5, 0, Math.PI * 2, true);
if (this.selectedPoint == i) {
ctx.fillStyle = '#AAAAAA';
ctx.fill();
}
ctx.stroke();
}
};
this.contains = function(mx, my) {
var i, j, c = false;
var testx = mx - this.x;
var testy = my - this.y;
for (var i = 0, j = nvert - 1; i < nvert; j = i++) {
if (((verty[i] > testy) != (verty[j] > testy)) && (testx < (vertx[j] - vertx[i]) * (testy - verty[i]) / (verty[j] - verty[i]) + vertx[i])) {
c = !c;
}
}
return c;
};
this.isPoint = function(mx, my) {
for (var i = 0; i < nvert; i++) {
dx = vertx[i] + this.x - mx
dy = verty[i] + this.y - my
if (dx * dx + dy * dy <= 25) {
...