Skip to content

Instantly share code, notes, and snippets.

@leekelleher
Created May 12, 2017 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leekelleher/babff2d3f8d8f61d69394533dd28218c to your computer and use it in GitHub Desktop.
Save leekelleher/babff2d3f8d8f61d69394533dd28218c to your computer and use it in GitHub Desktop.
Playing around with HTML Canvas to tint the colour of a white logo (on transparent background) PNG
<html>
<head>
<title>canvas</title>
</head>
<body bgcolor="white">
<h1>canvas</h1>
<canvas id="logo"></canvas>
<script>
var can = document.getElementById("logo");
can.width = 32;
can.height = 32;
var ctx = can.getContext("2d");
img = new Image();
img.src = "logo_white.png";
img.onload = function() {
ctx.drawImage(img, 0, 0);
var map = ctx.getImageData(0, 0, can.width, can.height);
var imdata = map.data;
// convert image to grayscale
var r,g,b,avg;
for(var p = 0, len = imdata.length; p < len; p += 4) {
r = imdata[p]
g = imdata[p + 1];
b = imdata[p + 2];
// alpha channel (p+3) is ignored
avg = Math.floor((r + g + b) / 3);
imdata[p] = imdata[p + 1] = imdata[p + 2] = avg;
}
ctx.putImageData(map, 0, 0);
// overlay filled rectangle using composition
ctx.globalCompositeOperation = "source-in";
ctx.globalAlpha = 1;
ctx.fillStyle = "#991d1d";
ctx.fillRect(0, 0, can.width, can.height);
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment