forked from minigolf2000/figma-closest-style-color-match
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ui.html
46 lines (40 loc) · 1.51 KB
/
ui.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<script>
// Decoding an image can be done by sticking it in an HTML canvas,
// since we can read individual pixels off the canvas.
async function decode(canvas, ctx, bytes) {
const url = URL.createObjectURL(new Blob([bytes]))
const image = await new Promise((resolve, reject) => {
const img = new Image()
img.onload = () => resolve(img)
img.onerror = () => reject()
img.src = url
})
canvas.width = image.width
canvas.height = image.height
ctx.drawImage(image, 0, 0)
const imageData = ctx.getImageData(0, 0, image.width, image.height)
return imageData
}
// Create an event handler to receive messages from the main thread
window.onmessage = async (event) => {
// Just get the bytes directly from the pluginMessage since that's
// the only type of message we'll receive in this plugin. In more
// complex plugins, you'll want to check the type of the message.
const bytes = event.data.pluginMessage
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
const imageData = await decode(canvas, ctx, bytes)
const pixels = imageData.data
const colors = []
// Construct the colors of pixel data
for (let i = 0; i < pixels.length; i += 4) {
colors.push({
r: pixels[i + 0] / 255,
g: pixels[i + 1] / 255,
b: pixels[i + 2] / 255,
a: pixels[i + 3] / 255,
})
}
window.parent.postMessage({pluginMessage: {colors, width: imageData.width}}, '*')
}
</script>