Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!doctype html>
- <html>
- <head>
- <title>The Solution</title>
- <meta charset="UTF-8" />
- </head>
- <body>
- <main>
- <img id="puzzle" src="puzzle.png">
- <canvas id="ourCanvas"></canvas>
- </main>
- <script>
- "use strict";
- window.onload = () => {
- /*
- We begin with a basic HTML file that displays the puzzle image and has
- a canvas which we will use for all of our image manipulations.
- */
- // Here we set the context for all subsequesnt manipulations of canvas data
- // as well as the image itself, so that we can draw it on canvas.
- let ctx = document.getElementById("ourCanvas").getContext("2d");
- let puzzleImage = document.getElementById("puzzle")
- // Now that we have an image we can use its dimensions to define the height
- // and width of the canvas we are about to use.
- ctx.canvas.width = puzzleImage.width;
- ctx.canvas.height = puzzleImage.height;
- // Now we have a ready canvas that we can draw on. Let's start by drawing
- // our puzzle so we can start figuring out the alpha channel business.
- ctx.drawImage(puzzleImage, 0, 0);
- // At this point all of the pixel data that interests us is contained
- // within the context, so all we have to do is grab and analyze it.
- let imageData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
- // Now we have an array of all pixel data the context contains. Every four
- // elements contain one pixel. [0] is R, [1] is G, [2] is B, and [3] is A.
- // Let's collect our alpha channel data.
- for (let i = 0; i < imageData.data.length; i += 4)
- {
- if (imageData.data[i+3] < 255) {
- // This is a pixel with some transparency. Let's save it as black.
- imageData.data[i] = 0;
- imageData.data[i+1] = 0;
- imageData.data[i+2] = 0;
- } else {
- // This is a pixel with no transparency. Let's save it as white.
- imageData.data[i] = 255;
- imageData.data[i+1] = 255;
- imageData.data[i+2] = 255;
- }
- // As we do not want any transparency in the new image we are creating
- // we will set the alpha channel to non-transparent across all pixels.
- imageData.data[i+3] = 255;
- }
- // At last we can now see what we ended up with. Let's draw this new image!
- ctx.putImageData(imageData, 0, 0);
- };
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement