I have an image of a font I would like to draw on an HTML5 Canvas. At first I though about separating each letter into a different image but decided having a sprite sheet would be much cleaner. A problem with that though, is that not all the letters are the same size. Some are a few pixels wider than other characters.
While looking on Google, I came across one way that some people handled the problem. They added a line under each character to represent that characters length and then draw the bottom most line of the font image into an off screen canvas and analyze it pixel by pixel.
I tried to implement my own version of that idea, but was unable to get that far. Before I invest more time on that idea, I would like to know if it's a good solution or if there is any better ways of achieving the same thing.
So far I have a few small snippets i'm trying to put together, like this code:
getImagePixels: function( image, x, y, width, height )
{
var canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
var ctx = canvas.getContext('2d');
ctx.drawImage( image, 0, 0, image.width, image.height );
return ctx.getImageData( x, y, width, height );
}
and this
loadFontImage: function( image )
{
// Draw the bottommost line of this font image into an offscreen canvas
// and analyze it pixel by pixel.
// A run of non-transparent pixels represents a character and its width
this.height = image.height-1;
this.widthMap = [];
this.indices = [];
var px = getImagePixels( image, 0, image.height-1, image.width, 1 );
var currentChar = 0;
var currentWidth = 0;
for( var x = 0; x < image.width; x++ )
{
var index = x * 4 + 3; // alpha component of this pixel
if( px.data[index] > 127 )
{
currentWidth++;
}
else if( px.data[index] < 128 && currentWidth )
{
this.widthMap.push( currentWidth );
this.indices.push( x-currentWidth );
currentChar++;
currentWidth = 0;
}
}
}
As I can't comment I will just write this as an answer:
You could also simply create or generate a javascript object with all the widths included:
var fontWidths = {
a: 8,
b: 8
....
};
That way the overhead doesn't happen every time you're going to write something to the canvas.
Related
I'm developing following case.
Html canvas created by JS.
There are a star image(loaded from png with alpha=0 background) and a diamond image(also loaded from png with alpha=0 background) on canvas.
diamond image is moving toward the star image.
when diamond image is completely behind the star image, like showing star image only and diamond image is completely behind the star image, alert("Hidden");
if more than one pixel of the diamond is shown, alert should not appear.
Since the alpha value of the background of the star is 0, which means star is not a rectangle, it is difficult to detect whether the star image is fully covering the diamond image.
Is there any library or way to detect whether an image is fully covered by other?
Or, does any one know the name of this algorithm so that I can implement in JS?
Thanks for any help!
For objects with unknown shape we can check if object is behind by using pixel check.
Here is a full example on how to do this:
ONLINE DEMO HERE
(GameAlchemist provided a modified version here)
/// basic allocations
var ctx = demo.getContext('2d'),
os = document.createElement('canvas'),
octx = os.getContext('2d'),
w = os.width = demo.width,
h = os.height = demo.height,
/// the images
urlD = 'http://i.imgur.com/U72xIMZ.png',
urlS = 'http://i.imgur.com/n5rgo11.png',
imgD = new Image(),
imgS = new Image(),
cnt = 2,
/// check region (optimized)
rect = [140, 140, 180, 60];
/// load images and when ready, start show
imgD.crossOrigin = imgS.crossOrigin = 'anonymous';
imgD.onload = imgS.onload = function() {
cnt--;
if (cnt === 0) start();
}
imgD.src = urlD;
imgS.src = urlS;
The main function checks the pixels within the region defined above. To optimize we can narrow down the search area. If you need to check if image is visible on the other size the region is simply extended to check that area as well.
The function compares an off-screen canvas with just the foremost image drawn against the "live" canvas where both background and foreground are drawn.
If live canvas = off-screen canvas that means the background image is not visible.
function start() {
octx.drawImage(imgS, (w - imgS.width) * 0.5, 20);
var x = -50,
buffer1 = octx.getImageData(rect[0], rect[1], rect[2], rect[3]).data,
len = buffer1.length;
loop();
function loop() {
ctx.clearRect(0, 0, w, h);
ctx.drawImage(imgD, x, 130);
ctx.drawImage(imgS, (w - imgS.width) * 0.5, 20);
if (compare() === true) {
info.innerHTML = 'Object is behind!';
return;
}
x += 2;
if (x < w) requestAnimationFrame(loop);
}
function compare() {
var buffer2 = ctx.getImageData(rect[0], rect[1], rect[2], rect[3]).data,
i = len - 1;
while(i--) {
if (buffer1[i] !== buffer2[i]) return false
}
return true;
}
}
I want to resize image using very simple algorithm. I have something like this:
var offtx = document.createElement('canvas').getContext('2d');
offtx.drawImage(imageSource, offsetX, offsetY, width, height, 0, 0, width, height);
this.imageData = offtx.getImageData(0, 0, width, height).data;
offtx.clearRect(0, 0, width, height);
for(var x = 0; x < this.width; ++x)
{
for(var y = 0; y < this.height; ++y)
{
var i = (y * this.width + x) * 4;
var r = this.imageData[i ];
var g = this.imageData[i+1];
var b = this.imageData[i+2];
var a = this.imageData[i+3];
offtx.fillStyle = "rgba("+r+","+g+","+b+","+(a/255)+")";
offtx.fillRect(0.5 + (x * this.zoomLevel) | 0, 0.5 + (y*this.zoomLevel) | 0, this.zoomLevel, this.zoomLevel);
}
}
this.imageData = offtx.getImageData(0, 0, this.width * this.zoomLevel, this.height * this.zoomLevel);
However, the problem I have with this solution, is that the image looses any transparency information that way. I don't know if this happens somewere in this algorithm, or maybe putImageData that I am using later to display that image is doing this, but I can't seem to be able to preserve transparency.
Each time I do this I create a canvas, I put the image on that canvas and use getImageData to get image from that canvas as you can see in the first lines of the code. Maybe there is no other way, so I might not mind that...
But the problem is I use two for loops to draw resized image and then use getImageData to store that image information. This is a wierd way to do it. I would prefer to create empty image data and fill it with all the original image information only resized. I can't grasp that with my mind, I can't image the loop structure for this. To show what I mean:
for(var x = 0; x < this.width; ++x)
{
for(var y = 0; y < this.height; ++y)
{
var i = (y * this.width + x) * 4;
var r = this.imageData[i ];
var g = this.imageData[i+1];
var b = this.imageData[i+2];
var a = this.imageData[i+3];
//I WOULD LIKE MAGIC TO HAPPEN HERE THAT WILL
//RESIZE THAT CURRENT PIXEL AND MOVE IT TO THE NEW IMAGE DATA RESIZED
//SO EVERYTHING IS DONE NICE AND CLEAN IN THIS LOOP WITHOUT THE
//GETIMAGEDATA LATER AND MAYBE SET TRANSPARENT PIXELS WHILE I'M AT IT
}
}
I can't figure out the MAGIC part.
Thank you for reading!
Why not just use the built-in drawImage combined with image smoothing disabled? Doing this operation in a loop is not only relative slow but also prone to errors (as you already discovered).
Doing it the following way will give you the "pixel art" look and will also preserve the alpha channel:
var factor = 4; /// will resize 4x
offtx.imageSmoothingEnabled = false; /// prefixed in some browsers
offtx.drawImage(imageSource, offsetX, offsetY, width, height,
0, 0, width * factor, height * factor);
Here is an online demo.
Try using this library I recently made which can load an image, resize it fixed width & height or precentage.
It does exactly what you need, and much more like converting canvas to base64, blob, etc...
var CanvaWork = new CanvaWork();
CanvaWork.canvasResizeAll(obj.canvas, function(canvases){
// "canvases" will be an array containing 3 canvases with different sizes depending on initial options
});
https://github.com/vnbenny/canvawork.js
Hope this helps you!
I know how to get this height of a font:
By placing the text in a div and getting offset height of the div.
But I would like to get this actual height (Which will depend on font family):
Is that in any way possible using web based programming?
Is there a simple solution? I think the answer is no.
If you're ok with a more involved (and processor-intensive) solution, you could try this:
Render the text to a canvas, then use canvasCtx.getImageData(..) to retrieve pixel information. Next you would do something similar to what this pseudo code describes:
first_y : null
last_y : null
for each y:
for each x:
if imageData[x][y] is black:
if first_y is null:
first_y = y
last_y = y
height = last_y - first_y
This basically looks for the top (lowest y-index) of the lettering (black pixels) and the bottom (highest y-index) then subtracts to retrieve the height.
I was writing the code while Jason answered, but I decided to post it anyway:
http://jsfiddle.net/adtn8/2/
If you follow the comments you should get the idea what's going on and why. It works pretty fast and it's not so complicated as it may sound. Checked with GIMP and it is accurate.
(code to be sure it wont be lost):
// setup variables
var c = document.createElement('canvas'),
div = document.getElementsByTagName('div')[0],
out = document.getElementsByTagName('output')[0];
// set canvas's size to be equal with div
c.width = div.offsetWidth;
c.height = div.offsetHeight;
var ctx = c.getContext('2d');
// get div's font from computed style and apply it to context
ctx.font = window.getComputedStyle(div).font;
// use color other than black because all pixels are 0 when black and transparent
ctx.fillStyle = '#bbb';
// draw the text near the bottom of the canvas
ctx.fillText(div.innerText, 0, div.offsetHeight);
// loop trough the canvas' data to find first colored pixel
var data = ctx.getImageData(0, 0, c.width, c.height).data,
minY = 0, len = data.length;
for (var i = 0; i < len; i += 4) {
// when you found it
if (data[i] != 0) {
// get pixel's y position
minY = Math.floor(i / 4 / c.width);
break;
}
}
// and print out the results
out.innerText = c.height - minY + 'px';
EDIT:
I even made jQuery plugin for this: https://github.com/maciek134/jquery-textHeight
Enjoy.
i am creating a image slider with html5 and jquery what i want to do is add 3 images on top of each other in one canvas and then get pixeldata of first image and remove some of it's pixels to show 2nd image through first i'm using jCanvas
Plug-in To Do This In Jquery What I've Got So Far Is
$(document).ready(function(){
function invert() {
$("canvas").setPixels({
x: 150, y: 150,
width: 100, height: 75,
// loop through each pixel
each: function(px) {
px.r = 255 - px.r;
px.g = 255 - px.g;
px.b = 255 - px.b;
px.a = 255 - px.a;
}
});
}
$("canvas")
.addLayer({
method: "drawImage",
source: "images/01.jpg",
x: 100, y: 100,
width: 480, height: 440
}).addLayer({
method: "drawImage",
source: "images/02.jpg",
x: 100, y: 100,
width: 380, height: 340
}).addLayer({
method: "drawImage",
source: "images/01.jpg",
x: 100, y: 100,
width: 280, height: 240,
load: invert
})
// Draw each layer on the canvas
.drawLayers();
});
Now What it Does Is making A hole In all the Images Means Erase all the Pixels Of That Portion Of all Images and Show the Background of canvas Is It Possible to Get Only Pixels Of Particular image or layer and Invert It is there any jquery plug-in available? any other way to do that? Any Help On this Will Be Very Useful To Me....Thanx In Advance....
Keep in mind that drawing on a canvas is like painting on paper, it doesn't remember what you drew before only what you have in the canvas right now so if you draw one image and then draw over it with another, the old picture is lost forever.
What you should do is keep all three images in three different buffers (simply load the three different images into three different image objects).
Then draw the top most image in the context.
When you wish to dissolve the first image into the second, instead of deleting pixels from the top image (which will only show the the background), simply use the same coordinates you would use to remove pixels from the first image to get the pixel data from the second image (the coordinates for deleting pixel from the top image can be used as indexes to the image data for the second image) and copy those values to the canvas, again using the same coordinates, for example:
If you algorithm leads you to first remove pixel x = 100, y = 175, use those coordinates to get the data from the buffer of the second image and copy that to the same coordinates in the canvas' image data.
Here's some code:
var width = 300;
var height = 300;
var img1 = new Image();
img1.src = "image1.png";
var img2 = new Image();
img2.src = "image2.png";
function go()
{
// Wait for the images to load
if ( !img1.complete || !img2.complete )
{
setTimeout( go, 100 );
return;
}
// Create a temporary canvas to draw the other images in the background
var tc = document.createElement( "canvas" );
tc.width = width;
tc.height = height;
var c2 = tc.getContext( "2d" );
// Draw the first image in the real canvas (change the ID to your canvas ID)
var c = document.getElementById( "myCanvas" ).getContext( "2d" );
c.drawImage( img1, 0, 0 );
var data1 = c.getImageData( 0, 0, width, height ); // Get the data for the first image
// Draw the second image in the temporary canvas (which is hidden) and get its data
c2.drawImage( img2, 0, 0 );
var data2 = c2.getImageData( 0, 0, width, height );
// Copy the data from the hidden image to the visible one
// This is where your magic comes into play, the following
// is just a very very simple example
var pix1 = data1.data;
var pix2 = data2.data;
for ( var x = 0; x < width; x++ )
{
for ( var y = 0; y < height; y++ )
{
var pos = ( ( y * width ) + x ) * 4;
pix1[ pos ] = pix2[ pos++ ];
pix1[ pos ] = pix2[ pos++ ];
pix1[ pos ] = pix2[ pos++ ];
pix1[ pos ] = pix2[ pos ];
}
}
// Redraw the visible canvas with the new data
c.putImageData( data1, 0, 0 );
}
window.onload = go;
The canvas element does not provide the ability to use layers like that. You may need to check add-ons like canvas collage or CanvasStack
Is there any way to check if a selected (x,y) point of a PNG image is transparent?
Building on Jeff's answer, your first step would be to create a canvas representation of your PNG. The following creates an off-screen canvas that is the same width and height as your image and has the image drawn on it.
var img = document.getElementById('my-image');
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
After that, when a user clicks, use event.offsetX and event.offsetY to get the position. This can then be used to acquire the pixel:
var pixelData = canvas.getContext('2d').getImageData(event.offsetX, event.offsetY, 1, 1).data;
Because you are only grabbing one pixel, pixelData is a four entry array containing the pixel's R, G, B, and A values. For alpha, anything less than 255 represents some level of transparency with 0 being fully transparent.
Here is a jsFiddle example: http://jsfiddle.net/thirtydot/9SEMf/869/ I used jQuery for convenience in all of this, but it is by no means required.
Note: getImageData falls under the browser's same-origin policy to prevent data leaks, meaning this technique will fail if you dirty the canvas with an image from another domain or (I believe, but some browsers may have solved this) SVG from any domain. This protects against cases where a site serves up a custom image asset for a logged in user and an attacker wants to read the image to get information. You can solve the problem by either serving the image from the same server or implementing Cross-origin resource sharing.
Canvas would be a great way to do this, as #pst said above. Check out this answer for a good example:
getPixel from HTML Canvas?
Some code that would serve you specifically as well:
var imgd = context.getImageData(x, y, width, height);
var pix = imgd.data;
for (var i = 0, n = pix.length; i < n; i += 4) {
console.log pix[i+3]
}
This will go row by row, so you'd need to convert that into an x,y and either convert the for loop to a direct check or run a conditional inside.
Reading your question again, it looks like you want to be able to get the point that the person clicks on. This can be done pretty easily with jquery's click event. Just run the above code inside a click handler as such:
$('el').click(function(e){
console.log(e.clientX, e.clientY)
}
Those should grab your x and y values.
The two previous answers demonstrate how to use Canvas and ImageData. I would like to propose an answer with runnable example and using an image processing framework, so you don't need to handle the pixel data manually.
MarvinJ provides the method image.getAlphaComponent(x,y) which simply returns the transparency value for the pixel in x,y coordinate. If this value is 0, pixel is totally transparent, values between 1 and 254 are transparency levels, finally 255 is opaque.
For demonstrating I've used the image below (300x300) with transparent background and two pixels at coordinates (0,0) and (150,150).
Console output:
(0,0): TRANSPARENT
(150,150): NOT_TRANSPARENT
image = new MarvinImage();
image.load("https://i.imgur.com/eLZVbQG.png", imageLoaded);
function imageLoaded(){
console.log("(0,0): "+(image.getAlphaComponent(0,0) > 0 ? "NOT_TRANSPARENT" : "TRANSPARENT"));
console.log("(150,150): "+(image.getAlphaComponent(150,150) > 0 ? "NOT_TRANSPARENT" : "TRANSPARENT"));
}
<script src="https://www.marvinj.org/releases/marvinj-0.7.js"></script>
Building on Brian Nickel's answer, only the wanted single pixel of the source image is drawn onto a 1*1 pixel canvas, which is more efficient than drawing the entire image just to get a single pixel:
function getPixel(img, x, y) {
let canvas = document.createElement('canvas');
canvas.width = 1;
canvas.height = 1;
canvas.getContext('2d').drawImage(img, x, y, 1, 1, 0, 0, 1, 1);;
let pixelData = canvas.getContext('2d').getImageData(0, 0, 1, 1).data;
return pixelData;
}
With : i << 2
const pixels = context.getImageData(x, y, width, height).data;
for (let i = 0, dx = 0; dx < data.length; i++, dx = i << 2)
{
if (pixels[dx+3] <= 8) { console.log("transparent x= " + i); }
}
Here's a consolidation of a few answers into a runnable snippet that lets you upload a file, hover to preview the RGB value of each pixel, then click to put the RGB in a div.
Pertinent to the original question, the last value (alpha) is the transparency. 0 is fully transparent and 255 is fully opaque.
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const input = document
.querySelector('input[type="file"]');
input.addEventListener("change", e => {
const image = new Image();
image.addEventListener("load", e => {
const {width, height} = image;
canvas.width = width;
canvas.height = height;
ctx.drawImage(image, 0, 0);
const {data} = ctx.getImageData(
0, 0, width, height
);
const rgb = (x, y) => {
const i = (x + y * width) * 4;
return data.slice(i, i + 4).join(", ");
};
canvas.addEventListener("mousemove", event => {
const {offsetX: x, offsetY: y} = event;
console.log(rgb(x, y));
});
canvas.addEventListener("click", event => {
const {offsetX: x, offsetY: y} = event;
document.querySelector("div")
.textContent = rgb(x, y);
});
});
image.addEventListener("error", () =>
console.error("failed")
);
image.src = URL
.createObjectURL(event.target.files[0]);
});
.as-console-wrapper {
height: 21px !important;
}
<div>
Upload image and mouseover to preview RGB. Click to select a value.
</div>
<form>
<input type="file">
</form>
<canvas></canvas>
References:
HTML5 Canvas - How to get adjacent pixels position from the linearized imagedata Uint8ClampedArray?
How to upload image into HTML5 canvas