Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Canvas to turn non-transparent pixels white

I'm looking for a way to take images (logos, app icons, etc.) and convert them to white (excluding transparency) using javascript/canvas.

Here's an example of what I'd like (using static images, obviously): http://jsfiddle.net/4ubyj/

like image 833
J. Chase Avatar asked Dec 05 '11 13:12

J. Chase


People also ask

How do you change the transparency of an image in canvas?

To adjust the general transparency of an image on your canvas - select it on your canvas, and click on the General Image Attribute option. Reduce the value of the Transparency slider to lower the overall opacity of the image.

How do you reduce opacity in canvas?

On the toolbar above the editor, click on Transparency. Click and drag the slider to adjust.


1 Answers

The canvas API has compositing methods specifically for things like "draw only on pixels that are not transparent in the original image." This is much easier than messing with the image data.

jsFiddle example (now with inlined image)

hat tip to @WilliamVanRensselaer's initial fiddle.

The composite operation you want is source-in, which means "draw the opaque parts of what I'm trying to paint only where they are on top of opaque pixels in the image being drawn upon."

HTML:

<a href="javascript:doIt()">paint non-transparent regions white</a><br>
<canvas id="canvas" width="600" height="200"></canvas>

Javascript:

var canvas = document.getElementById( "canvas" ),
    ctx = canvas.getContext( "2d" );

imgSrc = "http://d.pr/Td69+";
var b = document.getElementsByTagName("body")[0];
var i = document.createElement("img");
i.src = imgSrc;
i.style.setProperty("display", "none");
i.onload = function() {
    ctx.drawImage(i, 0, 0);
}
b.appendChild(i);

window.doIt = function() {
    ctx.globalCompositeOperation = "source-in";

    ctx.fillStyle = "#ffffff";
    ctx.fillRect(0, 0, 600, 200);
}

reference

like image 106
ellisbben Avatar answered Nov 05 '22 02:11

ellisbben