Last active
January 30, 2018 12:56
-
-
Save miketahani/df5497b78e29619089a8bfe8581dd299 to your computer and use it in GitHub Desktop.
cheap/hacky canvas hitboxes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<meta charset='utf-8'> | |
<style> | |
</style> | |
</head> | |
<body> | |
<div id='root'> | |
<canvas width='960' height='600'></canvas> | |
</div> | |
<script> | |
const canvas = document.querySelector('canvas') | |
const ctx = canvas.getContext('2d') | |
const width = +canvas.width | |
const height = +canvas.height | |
const rand = (mod = 1) => ~~(Math.random() * mod); | |
// you need to define your own function for converting some data to a unique color string | |
const createKey = rgb => `rgb(${rgb})` | |
// fake hitboxes | |
const hitboxes = Array(50).fill() | |
.map((_, id) => ({ | |
id, | |
x: rand(width), | |
y: rand(height), | |
radius: rand(100) + 20, | |
color: createKey([rand(255), rand(225), rand(225)]) | |
// color: createKey([id, id, id]) | |
})) | |
function drawOneCircle ({ x, y, radius, color }) { | |
ctx.beginPath() | |
ctx.arc(x, y, radius, 0, 2 * Math.PI) | |
ctx.fillStyle = color | |
ctx.fill() | |
} | |
function render () { | |
ctx.clearRect(0, 0, width, height) | |
hitboxes.forEach(drawOneCircle) | |
} | |
render() | |
// | |
// create a lookup table to match rgb colors to ids | |
const lookup = hitboxes.reduce((_lookup, obj) => { | |
_lookup[obj.color] = obj | |
return _lookup | |
}, {}) | |
const UNDEFINED = undefined | |
let activePixelKey = UNDEFINED | |
canvas.addEventListener('mouseout', _ => { | |
activePixelKey = UNDEFINED | |
render() | |
}) | |
canvas.addEventListener('mousemove', e => { | |
// get the rgb colors of the hovered pixel | |
const rgb = ctx.getImageData(e.offsetX, e.offsetY, 1, 1).data.slice(0, -1); | |
// create the object lookup key using the pixel data | |
const pixelKey = createKey(rgb) | |
// don't need to act if we're still hovering on the same object | |
if (pixelKey === activePixelKey) return; | |
const obj = { ...lookup[pixelKey] } | |
const { id = UNDEFINED, color } = obj | |
activePixelKey = pixelKey | |
// restore the screen to the original hitboxes | |
render() | |
// no matching object found, so bail (after restoring the original screen state above) | |
if (id === UNDEFINED) return; | |
// success! we have a matching object-- do something with it here | |
console.log(`%c ⬤ id = ${id}`, `color:${color}`) | |
drawOneCircle(obj) | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment