Created
May 16, 2019 18:57
-
-
Save hinzundcode/69cfed23bed337ea454043153d93e68a to your computer and use it in GitHub Desktop.
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> | |
<canvas id="canvas" style="width: 200px; height: 200px; border: 1px solid #000;" width=200 height=200></canvas> | |
<script type="module"> | |
const circle = (mx, my, r) => (x, y) => Math.pow(x - mx, 2) + Math.pow(y - my, 2) < Math.pow(r, 2); | |
let canvas = document.getElementById("canvas"); | |
let context = canvas.getContext("2d"); | |
let drawables = [ | |
{ | |
x: 0, y: 0, width: 100, height: 100, | |
mask: circle(50, 50, 50), | |
shade: (x, y) => [0, 255, 0] | |
}, | |
{ | |
x: 100, y: 100, width: 100, height: 100, | |
mask: (x, y) => true, | |
shade: (x, y) => [0, 255, 255] | |
}, | |
{ | |
x: 0, y: 0, width: 200, height: 200, | |
mask: (x, y) => true, | |
shade: (x, y) => [255, 0, 0] | |
}, | |
]; | |
function getPixel(x, y, drawables) { | |
for (let drawable of drawables) { | |
if (y >= drawable.y && y < drawable.y + drawable.height) { | |
if (x >= drawable.x && x < drawable.x + drawable.width) { | |
let innerX = x - drawable.x; | |
let innerY = y - drawable.y; | |
if (drawable.mask(innerX, innerY)) | |
return drawable.shade(innerX, innerY); | |
} | |
} | |
} | |
return [0, 0, 0]; | |
} | |
let line = context.createImageData(200, 1); | |
for (let y = 0; y < 200; y++) { | |
for (let x = 0; x < 200; x++) { | |
let [r, g, b] = getPixel(x, y, drawables); | |
line.data[x*4] = r; | |
line.data[x*4+1] = g; | |
line.data[x*4+2] = b; | |
line.data[x*4+3] = 255; | |
} | |
context.putImageData(line, 0, y); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment