Skip to content

Instantly share code, notes, and snippets.

@lewdev
Created October 29, 2023 02:59
Show Gist options
  • Select an option

  • Save lewdev/6c182bd9d8e2fd2b848b102bd3e0c7a3 to your computer and use it in GitHub Desktop.

Select an option

Save lewdev/6c182bd9d8e2fd2b848b102bd3e0c7a3 to your computer and use it in GitHub Desktop.
๐Ÿ–ผ Replace Canvas Color
<!doctype html>
<head><title>Replace Canvas color with transparent one</title></head>
<p>This code demonstrates taking "imageData" from the canvas and evaluating each pixel color and replacing it with an alpha value of "0".</p>
<p>This also can change the given color (#0F0, green, in this case) with another color.</p>
<p>This is useful when you can also get a PNG image to do this on.</p>
<canvas id="c"></canvas>
<script>
const EMOJI_CANVAS_SIZE = 200;
c.width = c.height = EMOJI_CANVAS_SIZE;
x = c.getContext`2d`;
x.fillStyle = "#0F0"; //fill background color
x.fillRect(0, 0, EMOJI_CANVAS_SIZE, EMOJI_CANVAS_SIZE);
x.fillText("๐Ÿ•", 0, 160);
//get image data from canvas
const imageData = x.getImageData(0, 0, EMOJI_CANVAS_SIZE, EMOJI_CANVAS_SIZE);
const { data } = imageData;
for (var i = 0; i < data.length; i += 4) {
const remove = data[i] === 0
&& data[i + 1] === 255//green
&& data[i + 2] === 0
&& data[i + 3] === 255//alpha;
data[i + 3] = remove ? 0 : data[i + 3];
}
x.putImageData(imageData, 0, 0); //if you comment this out, you will see the green background color
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment