UNPKG

2.25 kBJavaScriptView Raw
1// See files in confetti/*
2
3CSS.registerProperty({
4 name: '--extra-confettiNumber',
5 syntax: '<number>',
6 inherits: false,
7 initialValue: 30,
8});
9
10CSS.registerProperty({
11 name: '--extra-confettiLengthVariance',
12 syntax: '<number>',
13 inherits: false,
14 initialValue: 15,
15});
16
17CSS.registerProperty({
18 name: '--extra-confettiWeightVariance',
19 syntax: '<number>',
20 inherits: false,
21 initialValue: 4,
22});
23
24const worklet = `
25const getRandom = (min, max) => {
26 return Math.floor(Math.random() * (max - min + 1)) + min
27}
28
29if (typeof registerPaint !== 'undefined') {
30 class ExtraConfetti {
31 static get inputProperties() {
32 return ['--extra-confettiNumber','--extra-confettiLengthVariance', '--extra-confettiWeightVariance']
33 }
34
35 paint(ctx, size, properties) {
36 const confettiNum = properties.get('--extra-confettiNumber')
37 const minLength = 3
38 const maxLength = minLength + parseInt(properties.get('--extra-confettiLengthVariance'))
39 const minWeight = 1
40 const maxWeight = minWeight + parseInt(properties.get('--extra-confettiWeightVariance'))
41
42 for (var i = 0; i < confettiNum; i++) {
43 const x = Math.random() * size.width
44 const y = Math.random() * (size.height - maxLength)
45 const confettiLength = getRandom(minLength, maxLength)
46 const confettiWeight = getRandom(minWeight, maxWeight)
47
48 // Set Color
49 const hue = getRandom(0,360)
50 const sat = getRandom(90,100)
51 const light = getRandom(40,90)
52 const color = 'hsl(' + hue + 'deg,' + sat + '%,' + light + '%)'
53
54 // Set Paint Info
55 ctx.lineWidth = confettiWeight
56 ctx.strokeStyle = color
57
58 // Calculate New Position
59 const angle = getRandom(0,89)
60 const hypotenuse = confettiLength
61 const newX = x + Math.cos(angle) * hypotenuse
62 const newY = y + Math.sin(angle) * hypotenuse
63
64 // Paint
65 ctx.beginPath();
66 ctx.moveTo(x,y)
67 ctx.lineTo(newX, newY)
68 ctx.stroke()
69 }
70 }
71 }
72
73 registerPaint('extra-confetti', ExtraConfetti)
74}`
75
76const workletBlob = URL.createObjectURL(new Blob([worklet], { type: 'application/javascript' }))
77
78window.CSS.paintWorklet.addModule(workletBlob)
\No newline at end of file