-
Notifications
You must be signed in to change notification settings - Fork 0
/
blob_bubble.js
69 lines (61 loc) · 1.67 KB
/
blob_bubble.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
let points = [];
let isDrawing = false;
canvas.addEventListener('mousedown', function(event) {
isDrawing = true;
points.push([event.offsetX, event.offsetY]);
});
canvas.addEventListener('mousemove', function(event) {
if (isDrawing) {
points.push([event.offsetX, event.offsetY]);
drawBlob();
}
});
canvas.addEventListener('mouseup', function(event) {
isDrawing = false;
});
function drawBlob() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw the polygon
ctx.fillStyle = 'rgba(255, 0, 0, 0.5)';
ctx.beginPath();
ctx.moveTo(points[0][0], points[0][1]);
for (let i = 1; i < points.length; i++) {
ctx.lineTo(points[i][0], points[i][1]);
}
ctx.closePath();
ctx.fill();
// Calculate the largest circle that fits within the polygon
let minRadius = Number.MAX_VALUE;
let centerX = 0;
let centerY = 0;
for (let x = 0; x < canvas.width; x++) {
for (let y = 0; y < canvas.height; y++) {
if (ctx.isPointInPath(x, y)) {
let distance = getDistanceToPoint(x, y, points);
if (distance < minRadius) {
minRadius = distance;
centerX = x;
centerY = y;
}
}
}
}
// Draw the largest circle that fits within the polygon
ctx.fillStyle = 'rgba(0, 255, 0, 0.5)';
ctx.beginPath();
ctx.arc(centerX, centerY, minRadius, 0, 2 * Math.PI);
ctx.fill();
}
function getDistanceToPoint(x, y, points) {
let maxDistance = 0;
for (let i = 0; i < points.length; i++) {
let point = points[i];
let distance = Math.sqrt(Math.pow(x - point[0], 2) + Math.pow(y - point[1], 2));
if (distance > maxDistance) {
maxDistance = distance;
}
}
return maxDistance;
}