-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
70 lines (54 loc) · 2.14 KB
/
index.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change PNG Color</title>
</head>
<body>
<button onclick="start()">Change Color</button>
<br/><br/>
<img id="input" />
<br/>
<img id="output" />
<script>
function changeImageColor(url, color) {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext('2d');
if (!color.startsWith("#")) return;
var r = parseInt(color.substring(1, 3), 16);
var g = parseInt(color.substring(3, 5), 16);
var b = parseInt(color.substring(5, 7), 16);
const image = document.querySelector("#input");
image.crossOrigin = "Anonymous";
image.onload = function () {
canvas.width = image.width;
canvas.height = image.height;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(image, 0, 0);
// Get the pixel data
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data;
// Iterate through each pixel
for (let i = 0; i < data.length; i += 4) {
// Check if the pixel is not fully transparent
if (data[i + 3] !== 0) {
// Change black to red for non-transparent pixels
data[i] = r; // Red channel
data[i + 1] = g; // Green channel
data[i + 2] = b; // Blue channel
// Alpha channel (data[i + 3]) remains unchanged
}
}
// Put the modified pixel data back to the canvas
ctx.putImageData(imageData, 0, 0);
document.querySelector("#output").src = canvas.toDataURL("image/png");
};
image.src = url;
}
function start() {
changeImageColor("test.png", "#04AA6D");
}
</script>
</body>
</html>