-
Notifications
You must be signed in to change notification settings - Fork 7
/
canvas-medium.html
86 lines (70 loc) · 2.45 KB
/
canvas-medium.html
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<head>
<style>
body {
margin: 0;
}
#tooltip {
position: absolute;
transform: translate(-50%, 25px);
font-family: Sans-serif;
font-size: 12px;
padding: 3px;
border-radius: 3px;
color: lavender;
background: midnightblue;
opacity: 0.7;
visibility: hidden; /* by default */
}
</style>
<script src="//unpkg.com/canvas-color-tracker"></script>
<!--<script src="../dist/canvas-color-tracker.js"></script>-->
<script src="circle-generator.js"></script>
</head>
<body>
<canvas id="my-canvas"></canvas>
<div id="tooltip"></div>
<script>
const NUM_CIRCLES = 1e4;
const colorTracker = new ColorTracker();
const tooltip = document.getElementById('tooltip');
const canvas = document.getElementById('my-canvas');
const shadowCanvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const shadowCtx = shadowCanvas.getContext('2d');
// size canvases
[canvas, shadowCanvas].forEach(cv => {
cv.width = window.innerWidth;
cv.height = window.innerHeight;
});
const circles = genCircles(canvas.width, canvas.height, NUM_CIRCLES);
circles.forEach(circle => {
// Render in main canvas
ctx.beginPath();
ctx.arc(circle.x, circle.y, circle.r, 0, 2 * Math.PI, false);
ctx.fillStyle = 'rgba(197, 42, 27, 0.6)';
ctx.fill();
// Register in colorTracker
const shadowColor = colorTracker.register(circle);
if (!shadowColor) return; // registry is full
// Paint in shadow canvas (not bound to DOM)
shadowCtx.beginPath();
shadowCtx.arc(circle.x, circle.y, circle.r, 0, 2 * Math.PI, false);
shadowCtx.fillStyle = shadowColor;
shadowCtx.fill();
});
canvas.addEventListener('mousemove', ev => {
const mousePos = { offsetX: x, offsetY: y } = ev;
// Move tooltip
tooltip.style.left = `${mousePos.x}px`;
tooltip.style.top = `${mousePos.y}px`;
// Get px color of mouse position from shadow canvas
const pxColor = shadowCtx.getImageData(mousePos.x, mousePos.y, 1, 1).data;
// Retrieve original object by px color
const hoverObj = colorTracker.lookup(pxColor);
tooltip.style.visibility = hoverObj ? 'visible' : 'hidden';
tooltip.innerHTML = hoverObj
? `Circle id: ${hoverObj.id}<br>Center: ${hoverObj.x},${hoverObj.y}<br>Radius: ${hoverObj.r}`
: ''; // no object found
});
</script>
</body>