Last active
February 28, 2022 19:56
-
-
Save deflexor/62cc1bf3ff75f73b275a65b0ee7f0704 to your computer and use it in GitHub Desktop.
This file contains 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
import './index.css' | |
createCanvas = (el, width, height) -> | |
c = document.createElement 'canvas' | |
ctx = c.getContext('2d') | |
c.setAttribute 'width', width | |
c.setAttribute 'height', height | |
ctx.fillStyle = '#FFFFFF' | |
ctx.fillRect 0, 0, width, height | |
el.appendChild c | |
c | |
drawStar = (ctx, color, x, y, radius = 90) -> | |
alpha = 2 * Math.PI / 10 | |
starXY = [ | |
x | |
y | |
] | |
path = new Path2D | |
i = 11 | |
while i != 0 | |
r = radius * (i % 2 + 1) / 2 | |
omega = alpha * i | |
path.lineTo r * Math.sin(omega) + starXY[0], r * Math.cos(omega) + starXY[1] | |
i-- | |
ctx.fillStyle = color | |
ctx.fill(path) | |
path.closePath() | |
{ path, color } | |
trackMouseMove = (cnvs, ctx, stars) -> | |
cnvs.addEventListener 'mousemove', (event) -> | |
i = stars.length - 1 | |
inStar = false | |
while i >= 0 | |
if ctx.isPointInPath(stars[i].path, event.offsetX, event.offsetY) | |
inStar = true | |
break | |
i-- | |
if inStar | |
cnvs.style.cursor = 'pointer' | |
else | |
cnvs.style.cursor = 'default' | |
fillSmallCanvas = (smallCnvs, color) -> | |
sctx = smallCnvs.getContext('2d') | |
w = smallCnvs.getAttribute 'width' | |
h = smallCnvs.getAttribute 'height' | |
sctx.fillStyle = color | |
sctx.fillRect 0, 0, w, h | |
trackMouseClick = (cnvs, smallCnvs, ctx, stars) -> | |
cnvs.addEventListener 'mousedown', (event) -> | |
i = stars.length - 1 | |
clickedStar = -1 | |
while i >= 0 | |
if ctx.isPointInPath(stars[i].path, event.offsetX, event.offsetY) | |
clickedStar = i | |
break | |
i-- | |
color = '#FFFFFF' | |
if clickedStar >= 0 | |
color = stars[clickedStar].color | |
fillSmallCanvas smallCnvs, color | |
drawStars = (cnvs, smallCnvs) -> | |
app = document.getElementById 'app' | |
ctx = cnvs.getContext('2d') | |
colors = ['red', 'blue', 'green', 'yellow', 'black'] | |
stars = (drawStar ctx, c, 100 + 198 * (i % 3), (if i > 2 then 370 else 180) for c, i in colors) | |
trackMouseMove cnvs, ctx, stars | |
trackMouseClick cnvs, smallCnvs, ctx, stars | |
main = () -> | |
rootEl = document.getElementById 'app' | |
bigCnvs = createCanvas rootEl, 600, 600 | |
smallCnvs = createCanvas rootEl, 600, 50 | |
drawStars bigCnvs, smallCnvs | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment