-
Notifications
You must be signed in to change notification settings - Fork 0
/
canvas.html
91 lines (81 loc) · 2.69 KB
/
canvas.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<!DOCTYPE html>
<html>
<body> </body>
<script>
////////////////////////////////////////////////
// CANVAS WITH DEFAULT CONTEXT
////////////////////////////////////////////////
// Add Canvas to document
let canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 200;
const ctx = canvas.getContext('2d');
document.body.appendChild(canvas);
// Create SVG to embed
let img = document.createElement('img');
img.setAttribute('src', 'data:image/svg+xml,'
+ `<svg xmlns='http://www.w3.org/2000/svg' `
+ `width='200px' `
+ `height='200px'>`
+ `<foreignObject width='100%' height='100%'>`
+ `<html xmlns='http://www.w3.org/1999/xhtml'>`
+ `<body><h1>hello, world</h1></body>`
+ `</html>`
+ `</foreignObject>`
+ `</svg>`);
// Draw image
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, 200, 200);
ctx.drawImage(img, 0, 0);
// Extract Colors
let colors = new Map();
let pix = ctx.getImageData(0, 0, 200, 200).data;
for (let i = 0; i < pix.length; i = i+4){
let color = `rgb(${pix[i]}, ${pix[i+1]}, ${pix[i+2]})`;
if (colors.has(color)) {
colors.set(color, colors.get(color)+1);
} else {
colors.set(color, 0);
}
}
console.log(colors);
////////////////////////////////////////////////
// CANVAS WITH SMOOTHING / ANTIALIASING DISABLED
////////////////////////////////////////////////
// Add Canvas to document
canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 200;
const rufCtx = canvas.getContext('2d', {antialias: false});
rufCtx.imageSmoothingEnabled = false;
document.body.appendChild(canvas);
// Create SVG to embed
img = document.createElement('img');
img.setAttribute('src', 'data:image/svg+xml,'
+ `<svg xmlns='http://www.w3.org/2000/svg' `
+ `width='200px' `
+ `height='200px'>`
+ `<foreignObject width='100%' height='100%'>`
+ `<html xmlns='http://www.w3.org/1999/xhtml'>`
+ `<body><h1>hello, world</h1></body>`
+ `</html>`
+ `</foreignObject>`
+ `</svg>`);
// Draw image
rufCtx.fillStyle = 'white';
rufCtx.fillRect(0, 0, 200, 200);
rufCtx.drawImage(img, 0, 0);
// Extract Colors
colors = new Map();
pix = rufCtx.getImageData(0, 0, 200, 200).data;
for (let i = 0; i < pix.length; i = i+4){
let color = `rgb(${pix[i]}, ${pix[i+1]}, ${pix[i+2]})`;
if (colors.has(color)) {
colors.set(color, colors.get(color)+1);
} else {
colors.set(color, 0);
}
}
console.log(colors);
</script>
</html>