Created
June 16, 2014 08:06
-
-
Save mkoistinen/125e367efe26656cd3b6 to your computer and use it in GitHub Desktop.
Detecting 'opacity' of an image for text wrapping or whatever...
This file contains 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
function AlphaImage(img){ | |
var threshold = 40, | |
canvas, | |
ctx, | |
width, | |
height, | |
imgData; | |
width = img.width; | |
height = img.height; | |
canvas = document.createElement('canvas'); | |
canvas.width = width; | |
canvas.height = height; | |
ctx = canvas.getContext('2d'); | |
// Place the image on the canvas | |
ctx.drawImage(img, 0, 0); | |
// | |
// Get all of the pixelData of the image. | |
// | |
imgData = ctx.getImageData(0, 0, width, height); | |
// | |
// Given a height (as measure from the origin or top), return the width as | |
// defined as the distance from the first non-transparent pixel from the | |
// left edge to the right bounding rect edge. | |
// | |
this.getWidthForHeight = function(height) { | |
var c, alpha; | |
// | |
// Starting from the left edge, find the first pixel that is more opaque | |
// than our threshold. | |
// | |
for (c=0; c<width; c++) { | |
alpha = imgData.data[(height * width + c) * 4 + 3]; | |
if ( alpha > threshold ) { return width - c; } | |
} | |
// | |
// Welp, looks like this image is completely transparent here... at | |
// least within the threshold. | |
// | |
return 0; | |
}; | |
} | |
// To use this... | |
// Grab the first image found in the DOM... (jQuery) | |
var $img = $('img').eq(0); | |
// Now, instantiate AlphaImage with the image... | |
var ai = new AlphaImage( $img[0] ); | |
// Now you can quickly perform as many 'queries' as you like | |
// with this image. This is nice if you need to loop down | |
// the image (as I did). | |
var width, height; | |
for(height=0, height<$img.outHeight(); height++) { | |
// How much 'space' from the left edge at this | |
// height (from the top)? | |
width = ai(height); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment