Created
October 29, 2023 02:59
-
-
Save lewdev/6c182bd9d8e2fd2b848b102bd3e0c7a3 to your computer and use it in GitHub Desktop.
๐ผ Replace Canvas Color
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!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