J. Chase
J. Chase

Reputation: 1413

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/

Upvotes: 8

Views: 3401

Answers (2)

ellisbben
ellisbben

Reputation: 6371

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

Upvotes: 11

Will
Will

Reputation: 20235

Here's something to get you started. This basically changes the pixel to white if the alpha is not zero, you can make modifications if you want though.

Example: http://jsfiddle.net/Q27Qc/

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

// Put something on the canvas (can be an image)
ctx.font = "100px Arial";
ctx.fillText( "Google", 20, 130 );

// Get image data for part of the canvas (to see effects)
var img = ctx.getImageData( 20, 40, 80, 100 ),
    imgData = img.data;

// Loops through bytes and change pixel to white if alpha is not zero.
for ( var i = 0; i < imgData.length; i += 4 ) {
    if ( imgData[i + 3] !== 0 ) {
        imgData[i] = 255;
        imgData[i + 1] = 255;
        imgData[i + 2] = 255;
    }
}

// Draw the results
ctx.putImageData( img, 20, 40 );

Upvotes: 0

Related Questions