HTML5: Inverse text-color on canvas - html

I want to draw text on a canvas in the inverse color of the background (to make sure the text is readible no matter the background color). I believe in oldskool bitblt-ing, this was an XOR operation.
How to do this?

Update: most of the newer browsers now support the blending mode "difference" which can achieve the same result.
context.globalCompositeOperation = "difference";
Updated demo.
Old answer:
One should think that the XOR mode for composition would do this, but unfortunately canvas' XOR only XORs the alpha bits.
By applying the following code we can however receive a result such as this:
You can make an extension to the canvas like this:
CanvasRenderingContext2D.prototype.fillInversedText =
function(txt, x, y) {
//code - see below
}
Now you can call it on the context as the normal fillText, but with a slight change:
ctx.fillInversedText(txt, x, y);
For this to work we do the following first - measure text. Currently we can only calculate width of text and then assume the height. This may or may not work well as fonts can be very tall and so forth. Luckily this will change in the future, but for now:
var tw = this.measureText(txt).width;
var th = parseInt(ctx.font, '10');
th = (th === 0) ? 10 : th; //assume default if no font and size is set
Next thing we need to do is to setup an off-screen canvas to draw the text we want ot invert:
var co = document.createElement('canvas');
co.width = tw;
co.height = th;
Then draw the actual text. Color does not matter as we are only interested in the alpha channel for this canvas:
var octx = co.getContext('2d');
octx.font = this.font;
octx.textBaseline = 'top';
octx.fillText(txt, 0, 0);
Then we extract the pixel buffers for the area we want to draw the inverted text as well as all the pixels for the off-screen canvas which now contains our text:
var ddata = this.getImageData(x, y, tw, th);
var sdata = octx.getImageData(0, 0, tw, th);
var dd = ddata.data; //cache for increased speed
var ds = sdata.data;
var len = ds.length;
And then we invert each pixel where alpha channel for pixel is greater than 0.
for (var i = 0; i < len; i += 4) {
if (ds[i + 3] > 0) {
dd[i] = 255 - dd[i];
dd[i + 1] = 255 - dd[i + 1];
dd[i + 2] = 255 - dd[i + 2];
}
}
Finally put back the inverted image:
this.putImageData(ddata, x, y);
This may seem as a lot of operations, but it goes pretty fast.
Demo (warning if you are sensitive to flicker)
(the psychedelic background is just to have some variations as fiddle needs external images and most are prevented by CORS when we use pixel manipulation).

I've removed my old answer, as it did not solve the question. As of recently, there are new globalCompositeOperations that do all kinds of great things. I've created an example that shows how to obtain inverted text. In case that link breaks, the method is essentially this:
ctx.globalCompositeOperation = "difference";
ctx.fillStyle = "white";
//draw inverted things here
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation

Related

How to detect that the AlphaMaskFilter is completely gone in easeljs/createjs

I am doing a little scratch/reveal game based on the AlphaMaskFilter example:
http://createjs.com/demos/easeljs/AlphaMaskReveal.html
I want to detect that the the mask is completely gone, or use a threshold (90% scratched for example).
I read the doc on AlphaMaskFilter, shape and graphics objects and im not really sure how to achieve this.
Im not even sure i Have acess to the pixel information and check the alpha channel to detect it, but even so, I wonder if I will performance issue.
any help is welcome, thanks.
**** EDIT **** ADD TO THE ACCEPTED ANSWER ****
So, I was able to have the pct of transparency using the AlphaMapFilter (thanks Lanny).
The AlphaMapFilter offer you a mapping to the alpha channel of all the pixels.
Here is a little sample code that worked for me:
// mShapeToScratch is a createjs Shape. like in the http://createjs.com/demos/easeljs/AlphaMaskReveal.html example
var alphaMaskFilter = new createjs.AlphaMapFilter(mShapeToScratch.cacheCanvas);
var canvas = alphaMaskFilter.alphaMap;
var ctx = canvas.getContext("2d");
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var alphaData = imgData.data;
var pixelTotal = rect.h*rect.w;
var transparentPixel = 0;
// rect.h is the height of the image and rect.w is the width not shown in the example
for (var y = 0; y < rect.h; ++y)
{
for (var x=0; x < rect.w; ++x)
{
var pixelIdx = (y*rect.w + x);
if(alphaData[pixelIdx] > 128) // transparent will be 255.
{
transparentPixel++;
}
}
console.log("transparent % = " + transparentPixel/pixelTotal);
This example checks all the pixels, but it's pretty easy to check one every X pixels to speeds up checks as Lanny suggested.
The alpha mask uses canvas composite operation, and not pixel access, so without some completely custom approach, there isn't a great way to do this.
Iterating pixels (check out AlphaMapFilter as an example) would work - but could be fairly slow. Maybe checking every 4th, 10th, or 25th pixel would speed it up.
Cheers.

Finding the actual text height AS3

How can I get the actual height of a text in AS3 TextField? It appears that TextField.textHeight reports some fixed value that doesn't depend on the contents of a TextField.
The example code below produces the following:
text=o p g y d j
textWidth=120.8
textHeight=**96**
text=o
textWidth=15
textHeight=**96**
text=oW
textWidth=43.3
textHeight=**96**
Obviously, the height should be different for "o" and "p", etc.
The AS3 code:
import flash.text.TextField;
var format : TextFormat = new TextFormat();
format.font = "Times New Roman";
format.size = 30;
format.align = TextFormatAlign.CENTER;
var textField1 : TextField = new TextField();
textField1.defaultTextFormat = format;
textField1.selectable = false;
textField1.sharpness = 0;
textField1.embedFonts = true;
textField1.multiline = false;
textField1.height = 50;
textField1.width = 200;
textField1.x = 10;
textField1.y = 10;
addChild(textField1);
textField1.text = "o p g y d j";
trace("text=" + textField1.text);
trace("textWidth=" + textField1.textWidth);
trace("textHeight=" + textField1.textHeight);
textField1.text = "o";
trace("\ntext=" + textField1.text);
trace("textWidth=" + textField1.textWidth);
trace("textHeight=" + textField1.textHeight);
textField1.text = "oW";
trace("\ntext=" + textField1.text);
trace("textWidth=" + textField1.textWidth);
trace("textHeight=" + textField1.textHeight);
stop();
I guess TextField.textHeight is not the right variable, but what should I use instead?
Mark Fox is right that textHeight doesn't represent the actual height of text - and that the classic TextField in Flash doesn't have any support for getting the actual pixel height of rendered text. What textHeight does represent is the line height - which is its ascent (font's height above baseline), descent (font's height below baseline) and leading (space between lines) combined. As implied, the height is constant, based on the font's ascent and descent, not the actual text's. (Bearing this in mind, see Adobe's overview of the terms here - and note that TextLineMetrics won't help you either).
The "new" Flash Text Engine (flash.text.engine) does include properties to get the actual height of text rendered using that technology (e.g. TextLine.totalHeight) - but then we're getting into low level text rendering. If you need to use "classic" TextFields, this won't help you measuring the text anyway, since the Flash Text Engine has its own renderer, which doesn't necessarily render text at the same height and width as "classic" text.
What you can do instead is render the TextField to BitmapData then measure the bounds of the text:
// Create a completely transparent BitmapData:
var bmd:BitmapData = new BitmapData(
textfield.width,
textfield.height,
true,
0x00ffffff);
// Note that some cases may require you to render a Sprite/MovieClip
// CONTAINING the TextField for anything to get drawn.
// For example, AntiAliasType.ADVANCED (antialias for readability) is known to
// not be renderable in some cases - other settings may cause nothing to be
// rendered too. In that case, simply wrap add the TextField as a child of an
// otherwise empty Sprite/MovieClip, and pass that to draw() instead:
bmd.draw(textfield);
// This gets the bounds of pixels that are not completely transparent.
// Param 1: mask = specifies which color components to check (0xAARRGGBB)
// Param 2: color = is the color to check for.
// Param 3: findColor = whether to bound pixels OF the specified color (true),
// or NOT OF the specified color (false)
//
// In this case, we're interested in:
// 1: the alpha channel (0xff000000)
// 2: being 00 (0x00......)
// 3: and want the bounding box of pixels that DON'T meet that criterium (false)
var rect:Rectangle = bmd.getColorBoundsRect(0xff000000, 0x00000000, false);
// Do remember to dispose BitmapData when done with it:
bmd.dispose();
trace("text height = " + rect.height);
trace("text width = " + rect.width);
Note on accuracy
This may be completely irrelevant, depending on what you're going to use this for, but it's worth bearing in mind:
This method will obviously always return a result in whole pixels - the actual rendering of the glyphs, however, uses sub-pixels.
In other words, if you add the results of measuring the width of a "V" and an "o", and then compare that to the result of "Vo", they may not be the same. You might get "40 + 35 = 74". Ignoring that kerning etc. may push the letters closer together, the rendering of each letter (placement, anti-aliasing etc.) may also be different, depending on its context.
Your question highlights a legacy of weak semantics in the Flash typographic APIs.
The textHeight property represents the relative size of the typeface in pixels, it doesn't account for the pixel representation of the particular glyphs (the individual letter shapes) in the TextField.
As far as I know there is no direct programatic way to measure a glyph with Flash. However, you could bitmap the textfield and use getPixel to guess:
var tf:TextField = …your textfield…
var wide:int = tf.width;
var tall:int = tf.height;
var bmpd:BitmapData = new BitmapData(wide, tall, true,0xFFFFFFFF);
bmpd.draw( tf );
var totalPixels:int = wide * tall;
var index:int = totalPixels + 1;
var useIndex:int;
var xPixel:int;
var yPixel:int;
while (--index > 0) {
useIndex = index - 1;
xPixel = useIndex % wide;
yPixel = int(useIndex / wide);
var pixelColor:uint = bmpd.getPixel(xPixel, yPixel);
// write some logic to find the y extremes where the pixelColor values are not white (or whatever background color specified when you created the BitmapData)
}
You can do that by "textHeight";
// Create TextField
var tf:TextField = new TextField();
tf.wordWrap = true;
tf.multiline = true;
tf.selectable = false;
tf.antiAliasType = AntiAliasType.ADVANCED;
tf.autoSize = TextFieldAutoSize.LEFT; // It's should not be "=TextFieldAutoSize.NONE;"
tf.embedFonts = true;
tf.text = "Your text here";
this.addChild(tf);
trace(tf.textHeight);
Hope it will help

makin an image black and white / grayscale in html

Is there any way to convert the image so it appears as a gray scale. Changing rgb is not working as required.
As you probably know, screen color consists of 3 components: red, green and blue. Each component or color (for example, red) has a value from 0 to 255. The value 0 indicates there is no red color and the value 255 would be the brightest possible red color. To convert a color to grayscale you just need to calculate the average for all three components. This can be done using the simple formula below:
grayscalecolor = (red + green + blue) / 3;
Canvas Method
var canvas = document.createElement('canvas');
var canvasContext = canvas.getContext('2d');
var imgW = imgObj.width;
var imgH = imgObj.height;
canvas.width = imgW;
canvas.height = imgH;
canvasContext.drawImage(imgObj, 0, 0);
var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);
for(>var y = 0; y < imgPixels.height; y++){
for(>var x = 0; x < imgPixels.width; x++){
var i = (y * 4) * imgPixels.width + x * 4;
var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
imgPixels.data[i] = avg;
imgPixels.data[i + 1] = avg;
imgPixels.data[i + 2] = avg;
}
}
canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
return canvas.toDataURL();
Microsoft Internet Explorer does not support the CANVAS tag, but Microsoft does provide image manipulation through filters. The filter to use for converting images to grayscale is the filter named DXImageTransform.Microsoft.BasicImage.
imgObj.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayScale=1)';
If you're able to use HTML5 you could use a canvas, as seen here.
Google for "canvas grayscale image" the first link will be:
HTML 5 introduces Canvas object which can be used to draw and manipulate images. In this example, I used a Canvas to turn an image into grayscale. If your browser supports Canvas, you should see two images above: the normal image and the grayscale one. The grayscale one is not a separate image, it is generated by utilizing Canvas.
http://permadi.com/tutorial/jsCanvasGrayscale/index.html
If you want this to be done client side (on the browser) with a HTML you will need to use a Canvas. Example here: http://www.youtube.com/watch?v=QJa7tWScXS4
Use PaintbrushJS:
http://mezzoblue.github.com/PaintbrushJS/demo/
It lets you apply any number of filters including greyscale and works in most modern browsers. It's not a 'HTML' solution, that would not be possible without two images.
At least it works on most browsers, including ones which don't yet support HTML5.

Insert a single pixel into HTML5 canvas

I want to insert a pixel with a color, and I use this code:
context.fillStyle='RGB('+s[i]+')';
context.fillRect(i,y,1,1)
Is there a shorter way to do it? e.g. in a single line of code?
My main goal is to reduce the amount of code.
There really isn't a shorter way to do it besides the method you used above. You don't have to include a fillStyle every time so it essentially is only one line of code to fill a pixel.
Like Petteri pointed out there is another way to fill pixels, it involves manipulating the pixel data directly.
Live Demo
var canvasData = ctx.getImageData(0,0,canvasWidth,canvasHeight);
//color 100,100 red
canvasData.data[((100*(canvasData.width*4)) + (100*4)) + 0] = 255;
ctx.putImageData(canvasData,0,0);
also note with the above method you would need to repeat that line 3 times once for each component of the color. For example to set red, green, blue, and the alpha you would use
canvasData.data[((100*(canvasData.width*4)) + (100*4)) + 0] //red
canvasData.data[((100*(canvasData.width*4)) + (100*4)) + 1] //green
canvasData.data[((100*(canvasData.width*4)) + (100*4)) + 2] //blue
canvasData.data[((100*(canvasData.width*4)) + (100*4)) + 3] //alpha
granted you could have your data in an array, and just loop through that and color as needed.
You can edit the image data of the canvas directly. Here is a good example how to do it: http://beej.us/blog/2010/02/html5s-canvas-part-ii-pixel-manipulation/
No, there is no single line of code way to change a single pixel to one color. Well, there sort-of is.
As Petteri noted, there is a way to change each pixel directly, which will probably accomplish what you want. I assume what you want is to change one pixel to one color, and the next pixel to another color, etc.
For instance here is a function for desaturating a canvas. What it does is takes every pixel and averages the RGB values to be color-neutral (have no saturation). The result is a grayscale image.
function grayscale() {
var imageData = ctx.getImageData(0,0,can.width, can.height);
var pixels = imageData.data;
var numPixels = pixels.length;
ctx.clearRect(0, 0, can.width, can.height);
for (var i = 0; i < numPixels; i++) {
var average = (pixels[i*4] + pixels[i*4+1] + pixels[i*4+2]) /3;
// set red green and blue pixels to the average value
pixels[i*4] = average;
pixels[i*4+1] = average;
pixels[i*4+2] = average;
}
ctx.putImageData(imageData, 0, 0);
}
As you can see it is iterating over each pixel. It could be easily mofied to have each pixel changed as a one-liner.
Instead of:
pixels[i*4] = average;
pixels[i*4+1] = average;
pixels[i*4+2] = average;
You'd write:
// Take out 3 values starting at i*4 and add the new RGB for that pixel
pixels.splice(i*4,3,REDVALUE,GREENVALUE,BLUEVALUE);
Which would accomplish what you'd want. It's not the most efficient way under the sun, but it would accomplish your goal :)
fillStyle="rgb("+a[m];
fillRect(m,o,1,1);
Someone did with that :P

Bitmap conversion - Creating a transparent + black image from a B&W source

I have a whole bunch of jpg files that I need to use in a project, that for one reason or another cannot be altered. Each file is similar (handwriting), black pen on white BG. However I need to use these assets against a non-white background in my flash project, so I'm trying to do some client-side processing to get rid of the backgrounds using getPixel and setPixel32.
The code I am currently using currently uses a linear comparison, and while it works, the results are less than expected, as the shades of grey are getting lost in the mix. Moreso than just tweaking my parameters to get things looking proper, I get the feeling that my method for computing the RGBa value is weak.
Can anyone recommend a better solution than what I'm using below? Much appreciated!
private function transparify(data:BitmapData) : Bitmap {
// Create a new BitmapData with transparency to return
var newData:BitmapData = new BitmapData(data.width, data.height, true);
var orig_color:uint;
var alpha:Number;
var percent:Number;
// Iterate through each pixel using nested for loop
for(var x:int = 0; x < data.width; x++){
for (var y:int = 0; y < data.height; y++){
orig_color = data.getPixel(x,y);
// percent is the opacity percentage, white should be 0,
// black would be 1, greys somewhere in the middle
percent = (0xFFFFFF - orig_color)/0xFFFFFF;
// To get the alpha value, I multiply 256 possible values by
// my percentage, which gets multiplied by 0xFFFFFF to fit in the right
// value for the alpha channel
alpha = Math.round(( percent )*256)*0xFFFFFF;
// Adding the alpha value to the original color should give me the same
// color with an alpha channel added
var newCol = orig_color+alpha;
newData.setPixel32(x,y,newCol);
}
}
var newImg:Bitmap = new Bitmap(newData);
return newImg;
}
Since it's a white background, blendMode may give you a better result.