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/
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.
On the toolbar above the editor, click on Transparency. Click and drag the slider to adjust.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With