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 92 93 94 95 96 97 98 99 100 101 102
| <!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Changer les couleurs d'un PNG (Noir + transparent) </title>
<style>
* {
margin : 0;
padding : 0;
border : 0;
box-sizing: border-box;
}
body {
background-color : #c5ba23; /* mo edi à un color picker, et je l'utilise */
color : #a80c14; /* pour choisir une couleur moche de remplacement */
}
#origImg {
display : block;
width : 300px;
height : 200px;
margin : 20px;
}
#myCanvas {
margin : 20px;
width : 600px; /* pour tester un effet de déformation */
height : 200px;
}
</style>
</head>
<body>
<!--
<img id="origImg" src="test_1.png"> image en L=300px, H=200px
-->
<canvas id="myCanvas" ></canvas>
<script>
var imageObj = new Image();
imageObj.onload = function()
{
alterImage(this, '#a80c14', 300, 200)
}
imageObj.src = "test_1.png"; // url relative
// imageObj.src = document.getElementById( "origImg" ).src;
function alterImage(imageObj, newColor, wImg, hImg)
{
let
RGB = hex2rgb(newColor),
canvas = document.getElementById("myCanvas"),
ctx = canvas.getContext("2d");
// console.log("a", canvas.width, canvas.height )
// console.log("b", canvas.scrollWidth, canvas.scrollHeight )
canvas.setAttribute('width', wImg);
canvas.setAttribute('height', hImg);
ctx.drawImage(imageObj, 0, 0);
//let id = ctx.getImageData(0, 0, canvas.width, canvas.height);
let id = ctx.getImageData(0, 0, wImg, hImg);
// Iterate over data. Data is RGBA matrix so go by +=4 to get to next pixel data.
for (let i=0, iMax=id.data.length ; i < iMax; i +=4)
{
// Check if RGB == 0 (black)
if ( id.data[i] + id.data[i+1] + id.data[i+2] == 0 )
{
id.data[i] = RGB.r;
id.data[i+1] = RGB.g;
id.data[i+2] = RGB.b;
// id.data[i+3] reste inchangé, correspond au canal aplha ( opacité ) ?? ( à vérifier)
}
}
// redraw your altered data on the canvas.
ctx.putImageData(id, 0, 0);
}
function hex2rgb(hexStr)
{
// note: hexStr should be #rrggbb
let
hex = parseInt(hexStr.substring(1), 16),
r = (hex & 0xff0000) >> 16,
g = (hex & 0x00ff00) >> 8,
b = hex & 0x0000ff;
return {r, g, b};
}
</script>
</body>
</html> |
Partager