UNPKG

canvas-color-tracker

Version:

A utility to track objects on a canvas by unique px color

86 lines (70 loc) 2.55 kB
<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="//cdn.jsdelivr.net/npm/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', { willReadFrequently: true }); // 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>