JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas" width="500" height="500" style="outline: 1px solid #000">
JavaScript
function Point(x, y) {
this.x = x;
this.y = y;
}
function Vector(x, y) {
this.x = x;
this.y = y;
}
Vector.prototype.dot = function (r) {
return this.x * r.x + this.y * r.y;
};
Vector.prototype.subtract = function (v) {
return new Vector(this.x - v.x, this.y - v.y);
};
function Triangle(a, b, c) {
this.a = a;
this.b = b;
this.c = c;
this.setColor('#000');
}
Triangle.prototype.setColor = function (color) {
this.color = color;
};
Triangle.prototype.drawOn = function (canvas) {
var t = this;
canvas.contextFree(function (ctx) {
ctx.fillStyle = t.color;
ctx.beginPath();
ctx.moveTo(t.a.x, t.a.y);
ctx.lineTo(t.b.x, t.b.y);
ctx.lineTo(t.c.x, t.c.y);
ctx.lineTo(t.a.x, t.a.y);
ctx.fill();
});
};
Triangle.prototype.contains = function (point) {
var P = new Vector(point.x, point.y);
var A = new Vector(this.a.x, this.a.y);
var B = new Vector(this.b.x, this.b.y);
var C = new Vector(this.c.x, this.c.y);
// Compute vectors
var v0 = C.subtract(A);
var v1 = B.subtract(A);
var v2 = P.subtract(A);
// Compute dot products
var dot00 = v0.dot(v0);
var dot01 = v0.dot(v1);
var dot02 = v0.dot(v2);
var dot11 = v1.dot(v1);
var dot12 = v1.dot(v2);
// Compute barycentric coordinates
var invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
var v = (dot00 * dot12 - dot01 * dot02) * invDenom;
// Check if point is in triangle
return (u >= 0) && (v >= 0) && (u + v < 1);
};
function Composite(objects) {
this.objects = objects;
}
Composite.prototype.drawOn = function (canvas) {
var i;
for (i = 0; i < this.objects.length; i++) {
this.objects[i].drawOn(canvas);
}
};
Composite.prototype.contains = function (point) {
var i;
for (i = 0; i < this.objects.length; i++) {
if (this.objects[i].contains(point)) {
...