Calculate letter size in javascript - javascript

I need to calculate the exact size of the letter in javascript. The letter can have different font-size or font-family attributes, etc.
I tried to use div element for this, but this method gives only the size of the div, not letter.
<div style="display: inline; background-color: yellow; font-size: 53px; line-height:32px">A</div>
Does anybody know how to solve this issue?

This is basically not possible for the general case. Font kerning will result in variable "widths" of letters depending on the operating system, browser, etc etc, and based on which letters are next to each other. Font substitution may happen if the os+browser don't have the font you specify.
Perhaps re-asking the question with the higher-level goal you're shooting for might result in proposed other approaches to your problem that might be more fruitful?

As others have mentioned, this isn't possible to measure directly. But you can get at it in a more roundabout way: draw the letter onto a canvas and determine which pixels are filled in.
Here's a demo that does this. The meat is this function:
/**
* Draws a letter in the given font to an off-screen canvas and returns its
* size as a {w, h, descenderH} object.
* Results are cached.
*/
function measureLetter(letter, fontStyle) {
var cacheKey = letter + ' ' + fontStyle;
var cache = measureLetter.cache;
if (!cache) {
measureLetter.cache = cache = {};
}
var v = cache[cacheKey];
if (v) return v;
// Create a reasonably large off-screen <canvas>
var cnv = document.createElement('canvas');
cnv.width = '200';
cnv.height = '200';
// Draw the letter
var ctx = cnv.getContext('2d');
ctx.fillStyle = 'black';
ctx.font = fontStyle;
ctx.fillText(letter, 0.5, 100.5);
// See which pixels have been filled
var px = ctx.getImageData(0, 0, 200, 200).data;
var minX = 200, minY = 200, maxX = 0, maxY = 0;
var nonZero = 0;
for (var x = 0; x < 200; x++) {
for (var y = 0; y < 200; y++) {
var i = 4 * (x + 200 * y);
var c = px[i] + px[i + 1] + px[i + 2] + px[i + 3];
if (c === 0) continue;
nonZero++;
minX = Math.min(x, minX);
minY = Math.min(y, minY);
maxX = Math.max(x, maxX);
maxY = Math.max(y, maxY);
}
}
var o = {w: maxX - minX, h: maxY - minY, descenderH: maxY - 100};
cache[cacheKey] = o;
return o;
}
Note that this is sensitive to antialiasing—the results might be off by a pixel.

#Irongaze.com is right that your fonts, depending on conditions, will have varying actual sizes.
If you want to calibrate for a specific letter, I believe element.getBoundingClientRect() will give you useful coordinates. Be sure to fully reset the container wich you are using as a control box. Mind that on different systems you might get different results.
jsFiddle
Please note that this will not give you the size of the actual visible part of the letter, but the size of the container it determines. line-height for example, will not change the actual letter size, but it will affect other letters' positioning. Be aware of that.
It will help us if you describe the problem you are trying to solve. There might be better solutions.

Related

CSS `line-height` relative to baseline (with JS?) [duplicate]

I'm trying to do something that should be very simple but I've spent my day between failures and forums..
I would like to adjust my font in order to match my baseline. On indesign it's one click but in css it looks like the most difficult thing on earth..
Lets take a simple example with rational values.
On this image I have a baseline every 20px.
So for my <body> I do:
<style>
body {font-size:16px; line-height:20px;}
</style>
Everything works perfectly. My paragraph matchs the baseline.
But when I'm scripting my <h> that doesn't match the baseline anymore.. what am I doing wrong? That should follow my baseline, shouldn't it?
<style type="text/css">
body{font-size: 16px; line-height: 20px;}
h1{font-size: 5em; line-height: 1.25em;}
h2{font-size: 4em; line-height: 1.25em;}
h3{font-size: 3em; line-height: 1.25em;}
h4{font-size: 2em; line-height: 1.25em;}
</style>
ps: 20/16=1.25em
In my inspector, computed returns the expected values
h1{font-size: 84px; line-height: 100px;}
h2{font-size: 68px; line-height: 80px;}
h3{font-size: 52px; line-height: 60px;}
h4{font-size: 36px; line-height: 40px;}
So that should display something like this no?
It is a bit complicated - you have to measure the fonts first (as InDesign does) and calculate "line-height", the thing you called "bottom_gap" and some other stuff
I'm pretty sure we can do something in JavaScript..
You are right – but for Typography JS is used to calculate the CSS (depending on the font metrics)
Did demo the first step (measuring a font) here
https://codepen.io/sebilasse/pen/gPBQqm
It is just showing graphically what is measured [for the technical background]
This measuring is needed because every font behaves totally different in a "line".
Here is a generator which could generate such a Typo CSS:
https://codepen.io/sebilasse/pen/BdaPzN
A function to measure could be based on <canvas> and look like this :
function getMetrics(fontName, fontSize) {
// NOTE: if there is no getComputedStyle, this library won't work.
if(!document.defaultView.getComputedStyle) {
throw("ERROR: 'document.defaultView.getComputedStyle' not found. This library only works in browsers that can report computed CSS values.");
}
if (!document.querySelector('canvas')) {
var _canvas = document.createElement('canvas');
_canvas.width = 220; _canvas.height = 220;
document.body.appendChild(_canvas);
}
// Store the old text metrics function on the Canvas2D prototype
CanvasRenderingContext2D.prototype.measureTextWidth = CanvasRenderingContext2D.prototype.measureText;
/**
* Shortcut function for getting computed CSS values
*/
var getCSSValue = function(element, property) {
return document.defaultView.getComputedStyle(element,null).getPropertyValue(property);
};
/**
* The new text metrics function
*/
CanvasRenderingContext2D.prototype.measureText = function(textstring) {
var metrics = this.measureTextWidth(textstring),
fontFamily = getCSSValue(this.canvas,"font-family"),
fontSize = getCSSValue(this.canvas,"font-size").replace("px",""),
isSpace = !(/\S/.test(textstring));
metrics.fontsize = fontSize;
// For text lead values, we meaure a multiline text container.
var leadDiv = document.createElement("div");
leadDiv.style.position = "absolute";
leadDiv.style.margin = 0;
leadDiv.style.padding = 0;
leadDiv.style.opacity = 0;
leadDiv.style.font = fontSize + "px " + fontFamily;
leadDiv.innerHTML = textstring + "<br/>" + textstring;
document.body.appendChild(leadDiv);
// Make some initial guess at the text leading (using the standard TeX ratio)
metrics.leading = 1.2 * fontSize;
// Try to get the real value from the browser
var leadDivHeight = getCSSValue(leadDiv,"height");
leadDivHeight = leadDivHeight.replace("px","");
if (leadDivHeight >= fontSize * 2) { metrics.leading = (leadDivHeight/2) | 0; }
document.body.removeChild(leadDiv);
// if we're not dealing with white space, we can compute metrics
if (!isSpace) {
// Have characters, so measure the text
var canvas = document.createElement("canvas");
var padding = 100;
canvas.width = metrics.width + padding;
canvas.height = 3*fontSize;
canvas.style.opacity = 1;
canvas.style.fontFamily = fontFamily;
canvas.style.fontSize = fontSize;
var ctx = canvas.getContext("2d");
ctx.font = fontSize + "px " + fontFamily;
var w = canvas.width,
h = canvas.height,
baseline = h/2;
// Set all canvas pixeldata values to 255, with all the content
// data being 0. This lets us scan for data[i] != 255.
ctx.fillStyle = "white";
ctx.fillRect(-1, -1, w+2, h+2);
ctx.fillStyle = "black";
ctx.fillText(textstring, padding/2, baseline);
var pixelData = ctx.getImageData(0, 0, w, h).data;
// canvas pixel data is w*4 by h*4, because R, G, B and A are separate,
// consecutive values in the array, rather than stored as 32 bit ints.
var i = 0,
w4 = w * 4,
len = pixelData.length;
// Finding the ascent uses a normal, forward scanline
while (++i < len && pixelData[i] === 255) {}
var ascent = (i/w4)|0;
// Finding the descent uses a reverse scanline
i = len - 1;
while (--i > 0 && pixelData[i] === 255) {}
var descent = (i/w4)|0;
// find the min-x coordinate
for(i = 0; i<len && pixelData[i] === 255; ) {
i += w4;
if(i>=len) { i = (i-len) + 4; }}
var minx = ((i%w4)/4) | 0;
// find the max-x coordinate
var step = 1;
for(i = len-3; i>=0 && pixelData[i] === 255; ) {
i -= w4;
if(i<0) { i = (len - 3) - (step++)*4; }}
var maxx = ((i%w4)/4) + 1 | 0;
// set font metrics
metrics.ascent = (baseline - ascent);
metrics.descent = (descent - baseline);
metrics.bounds = { minx: minx - (padding/2),
maxx: maxx - (padding/2),
miny: 0,
maxy: descent-ascent };
metrics.height = 1+(descent - ascent);
} else {
// Only whitespace, so we can't measure the text
metrics.ascent = 0;
metrics.descent = 0;
metrics.bounds = { minx: 0,
maxx: metrics.width, // Best guess
miny: 0,
maxy: 0 };
metrics.height = 0;
}
return metrics;
};
Note that you also need a good "reset.css" to reset the browser margins and paddings.
You click "show CSS" and you can also use the generated CSS to mix multiple fonts:
If they have different base sizes, normalize the second:
var factor = CSS1baseSize / CSS2baseSize;
and now recalculate each font in CSS2 with
var size = size * factor;
See a demo in https://codepen.io/sebilasse/pen/oENGev?editors=1100
What if it comes to images?
The following demo uses two fonts with the same metrics plus an extra JS part. It is needed to calculate media elements like images for the baseline grid :
https://codepen.io/sebilasse/pen/ddopBj

Cropping an HTML canvas to the width/height of its visible pixels (content)?

Can an HTML canvas element be internally cropped to fit its content?
For example, if I have a 500x500 pixel canvas with only a 10x10 pixel square at a random location inside it, is there a function which will crop the entire canvas to 10x10 by scanning for visible pixels and cropping?
Edit: this was marked as a duplicate of Javascript Method to detect area of a PNG that is not transparent but it's not. That question details how to find the bounds of non-transparent content in the canvas, but not how to crop it. The first word of my question is "cropping" so that's what I'd like to focus on.
A better trim function.
Though the given answer works it contains a potencial dangerous flaw, creates a new canvas rather than crop the existing canvas and (the linked region search) is somewhat inefficient.
Creating a second canvas can be problematic if you have other references to the canvas, which is common as there are usually two references to the canvas eg canvas and ctx.canvas. Closure could make it difficult to remove the reference and if the closure is over an event you may never get to remove the reference.
The flaw is when canvas contains no pixels. Setting the canvas to zero size is allowed (canvas.width = 0; canvas.height = 0; will not throw an error), but some functions can not accept zero as an argument and will throw an error (eg ctx.getImageData(0,0,ctx.canvas.width,ctx.canvas.height); is common practice but will throw an error if the canvas has no size). As this is not directly associated with the resize this potencial crash can be overlooked and make its way into production code.
The linked search checks all pixels for each search, the inclusion of a simple break when an edge is found would improve the search, there is still an on average quicker search. Searching in both directions at the same time, top and bottom then left and right will reduce the number of iterations. And rather than calculate the address of each pixel for each pixel test you can improve the performance by stepping through the index. eg data[idx++] is much quicker than data[x + y * w]
A more robust solution.
The following function will crop the transparent edges from a canvas in place using a two pass search, taking in account the results of the first pass to reduce the search area of the second.
It will not crop the canvas if there are no pixels, but will return false so that action can be taken. It will return true if the canvas contains pixels.
There is no need to change any references to the canvas as it is cropped in place.
// ctx is the 2d context of the canvas to be trimmed
// This function will return false if the canvas contains no or no non transparent pixels.
// Returns true if the canvas contains non transparent pixels
function trimCanvas(ctx) { // removes transparent edges
var x, y, w, h, top, left, right, bottom, data, idx1, idx2, found, imgData;
w = ctx.canvas.width;
h = ctx.canvas.height;
if (!w && !h) { return false }
imgData = ctx.getImageData(0, 0, w, h);
data = new Uint32Array(imgData.data.buffer);
idx1 = 0;
idx2 = w * h - 1;
found = false;
// search from top and bottom to find first rows containing a non transparent pixel.
for (y = 0; y < h && !found; y += 1) {
for (x = 0; x < w; x += 1) {
if (data[idx1++] && !top) {
top = y + 1;
if (bottom) { // top and bottom found then stop the search
found = true;
break;
}
}
if (data[idx2--] && !bottom) {
bottom = h - y - 1;
if (top) { // top and bottom found then stop the search
found = true;
break;
}
}
}
if (y > h - y && !top && !bottom) { return false } // image is completely blank so do nothing
}
top -= 1; // correct top
found = false;
// search from left and right to find first column containing a non transparent pixel.
for (x = 0; x < w && !found; x += 1) {
idx1 = top * w + x;
idx2 = top * w + (w - x - 1);
for (y = top; y <= bottom; y += 1) {
if (data[idx1] && !left) {
left = x + 1;
if (right) { // if left and right found then stop the search
found = true;
break;
}
}
if (data[idx2] && !right) {
right = w - x - 1;
if (left) { // if left and right found then stop the search
found = true;
break;
}
}
idx1 += w;
idx2 += w;
}
}
left -= 1; // correct left
if(w === right - left + 1 && h === bottom - top + 1) { return true } // no need to crop if no change in size
w = right - left + 1;
h = bottom - top + 1;
ctx.canvas.width = w;
ctx.canvas.height = h;
ctx.putImageData(imgData, -left, -top);
return true;
}
Can an HTML canvas element be internally cropped to fit its content?
Yes, using this method (or a similar one) will give you the needed coordinates. The background don't have to be transparent, but uniform (modify code to fit background instead) for any practical use.
When the coordinates are obtained simply use drawImage() to render out that region:
Example (since no code is provided in question, adopt as needed):
// obtain region here (from linked method)
var region = {
x: x1,
y: y1,
width: x2-x1,
height: y2-y1
};
var croppedCanvas = document.createElement("canvas");
croppedCanvas.width = region.width;
croppedCanvas.height = region.height;
var cCtx = croppedCanvas.getContext("2d");
cCtx.drawImage(sourceCanvas, region.x, region.y, region.width, region.height,
0, 0, region.width, region.height);
Now croppedCanvas contains only the cropped part of the original canvas.

Use Javascript to get Maximum font size in canvas

I am drawing a canvas that needs to be on full available screen (100% width and height). I set the width and height of canvas using javascript like this
var w = window.innerWidth;
var h = window.innerHeight;
var canvas = document.getElementById("myCanvas");
canvas.width = w;
canvas.height = h;
After setting the canvas, I need to draw some text in it which needs to get the maximum available font size. Please help me finding the way how can I display text with maximum font size. The text may contain a single character (both upper and small case) or a string and can also contain numbers. I need to do it with javascript not jquery.
Thank you for your help.
Challenge
As canvas' measureText doesn't currently support measuring height (ascent + descent) we need to do a little DOM trick to get the line-height.
As the actual height of a font - or typeface - does not necessarily (rarely) correspond with the font-size, we need a more accurate way of measuring it.
Solution
Fiddle demo
The result will be a vertical aligned text which always fit the canvas in width.
This solution will automatically get the optimal size for the font.
The first function is to wrap the measureText to support height. If the new implementation of the text metrics isn't available then use DOM:
function textMetrics(ctx, txt) {
var tm = ctx.measureText(txt),
w = tm.width,
h, el; // height, div element
if (typeof tm.fontBoundingBoxAscent === "undefined") {
// create a div element and get height from that
el = document.createElement('div');
el.style.cssText = "position:fixed;font:" + ctx.font +
";padding:0;margin:0;left:-9999px;top:-9999px";
el.innerHTML = txt;
document.body.appendChild(el);
h = parseInt(getComputedStyle(el).getPropertyValue('height'), 10);
document.body.removeChild(el);
}
else {
// in the future ...
h = tm.fontBoundingBoxAscent + tm.fontBoundingBoxDescent;
}
return [w, h];
}
Now we can loop to find the optimal size (here not very optimized, but works for the purpose - and I wrote this just now so there might be bugs in there, one being if text is just a single char that doesn't exceed width before height).
This function takes minimum two arguments, context and the text, the others are optional such as font name (name only), tolerance [0.0, 1.0] (default 0.02 or 2%) and style (ie. bold, italic etc.):
function getOptimalSize(ctx, txt, fontName, tolerance, tolerance, style) {
tolerance = (tolerance === undefined) ? 0.02 : tolerance;
fontName = (fontName === undefined) ? 'sans-serif' : fontName;
style = (style === undefined) ? '' : style + ' ';
var w = ctx.canvas.width,
h = ctx.canvas.height,
current = h,
i = 0,
max = 100,
tm,
wl = w - w * tolerance * 0.5,
wu = w + w * tolerance * 0.5,
hl = h - h * tolerance * 0.5,
hu = h + h * tolerance * 0.5;
for(; i < max; i++) {
ctx.font = style + current + 'px ' + fontName;
tm = textMetrics(ctx, txt);
if ((tm[0] >= wl && tm[0] <= wu)) {
return tm;
}
if (tm[1] > current) {
current *= (1 - tolerance);
} else {
current *= (1 + tolerance);
}
}
return [-1, -1];
}
Try this.
FIDDLE DEMO
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var x = canvas.width / 2;
var y = canvas.height / 2 - 10;
var text = 'I M # CENTER!';
context.font = '10pt Calibri'; //try changing values 10,15,20
context.textAlign = 'center';
context.fillStyle = 'red';
context.fillText(text, x, y);
You can provide your conditions depending on the window size.Create a simple function like following:
function Manipulate_FONT(window.widht, window.height) {
if (window.widht == something && window.height == something) {
font_size = xyz //put this in ---> context.font = '10pt Calibri'
}
}

randomly mapping divs

I am creating a new "whack-a-mole" style game where the children have to hit the correct numbers in accordance to the question. So far it is going really well, I have a timer, count the right and wrong answers and when the game is started I have a number of divs called "characters" that appear in the container randomly at set times.
The problem I am having is that because it is completely random, sometimes the "characters" appear overlapped with one another. Is there a way to organize them so that they appear in set places in the container and don't overlap when they appear.
Here I have the code that maps the divs to the container..
function randomFromTo(from, to) {
return Math.floor(Math.random() * (to - from + 1) + from);
}
function scramble() {
var children = $('#container').children();
var randomId = randomFromTo(1, children.length);
moveRandom('char' + randomId);
}
function moveRandom(id) {
var cPos = $('#container').offset();
var cHeight = $('#container').height();
var cWidth = $('#container').width();
var pad = parseInt($('#container').css('padding-top').replace('px', ''));
var bHeight = $('#' + id).height();
var bWidth = $('#' + id).width();
maxY = cPos.top + cHeight - bHeight - pad;
maxX = cPos.left + cWidth - bWidth - pad;
minY = cPos.top + pad;
minX = cPos.left + pad;
newY = randomFromTo(minY, maxY);
newX = randomFromTo(minX, maxX);
$('#' + id).css({
top: newY,
left: newX
}).fadeIn(100, function () {
setTimeout(function () {
$('#' + id).fadeOut(100);
window.cont++;
}, 1000);
});
I have a fiddle if it helps.. http://jsfiddle.net/pUwKb/8/
As #aug suggests, you should know where you cannot place things at draw-time, and only place them at valid positions. The easiest way to do this is to keep currently-occupied positions handy to check them against proposed locations.
I suggest something like
// locations of current divs; elements like {x: 10, y: 40}
var boxes = [];
// p point; b box top-left corner; w and h width and height
function inside(p, w, h, b) {
return (p.x >= b.x) && (p.y >= b.y) && (p.x < b.x + w) && (p.y < b.y + h);
}
// a and b box top-left corners; w and h width and height; m is margin
function overlaps(a, b, w, h, m) {
var corners = [a, {x:a.x+w, y:a.y}, {x:a.x, y:a.y+h}, {x:a.x+w, y:a.y+h}];
var bWithMargins = {x:b.x-m, y:b.y-m};
for (var i=0; i<corners.length; i++) {
if (inside(corners[i], bWithMargins, w+2*m, h+2*m) return true;
}
return false;
}
// when placing a new piece
var box;
while (box === undefined) {
box = createRandomPosition(); // returns something like {x: 15, y: 92}
for (var i=0; i<boxes.length; i++) {
if (overlaps(box, boxes[i], boxwidth, boxheight, margin)) {
box = undefined;
break;
}
}
}
boxes.push(box);
Warning: untested code, beware the typos.
The basic idea you will have to implement is that when a random coordinate is chosen, theoretically you SHOULD know the boundaries of what is not permissible and your program should know not to choose those places (whether you find an algorithm or way of simply disregarding those ranges or your program constantly checks to make sure that the number chosen isn't within the boundary is up to you. the latter is easier to implement but is a bad way of going about it simply because you are entirely relying on chance).
Let's say for example coordinate 50, 70 is selected. If the picture is 50x50 in size, the range of what is allowed would exclude not only the dimensions of the picture, but also 50px in all directions of the picture so that no overlap may occur.
Hope this helps. If I have time, I might try to code an example but I hope this answers the conceptual aspect of the question if that is what you were having trouble with.
Oh and btw forgot to say really great job on this program. It looks awesome :)
You can approach this problem in at least two ways (these two are popped up in my head).
How about to create a 2 dimensional grid segmentation based on the number of questions, the sizes of the question panel and an array holding the position of each question coordinates and then on each time frame to position randomly these panels on one of the allowed coordinates.
Note: read this article for further information: http://eloquentjavascript.net/chapter8.html
The second approach follow the same principle, but this time to check if the panel overlap the existing panel before you place it on the canvas.
var _grids;
var GRID_SIZE = 20 //a constant holding the panel size;
function createGrids() {
_grids = new Array();
for (var i = 0; i< stage.stageWidth / GRID_SIZE; i++) {
_grids[i] = new Array();
for (var j = 0; j< stage.stageHeight / GRID_SIZE; j++) {
_grids[i][j] = new Array();
}
}
}
Then on a separate function to create the collision check. I've created a gist for collision check in Actionscript, but you can use the same principle in Javascript too. I've created this gist for inspirational purposes.
Just use a random number which is based on the width of your board and then modulo with the height...
You get a cell which is where you can put the mole.
For the positions the x and y should never change as you have 9 spots lets say where the mole could pop up.
x x x
x x x
x x x
Each cell would be sized based on % rather then pixels and would allow re sizing the screen
1%3 = 1 (x)
3%3 = 0 (y)
Then no overlap is possible.
Once the mole is positioned it can be show or hidden or moved etc based on some extended logic if required.
If want to keep things your way and you just need a quick re-position algorithm... just set the NE to the SW if the X + width >= x of the character you want to check by setting the x = y+height of the item which overlaps. You could also enforce that logic in the drawing routine by caching the last x and ensuring the random number was not < last + width of the item.
newY = randomFromTo(minY, maxY);
newX = randomFromTo(minX, maxX); if(newX > lastX + characterWidth){ /*needful*/}
There could still however be overlap...
If you wanted to totally eliminate it you would need to keep track of state such as where each x was and then iterate that list to find a new position or position them first and then all them to move about randomly without intersecting which would would be able to control with just padding from that point.
Overall I think it would be easier to just keep X starting at 0 and then and then increment until you are at a X + character width > greater then the width of the board. Then just increase Y by character height and Set X = 0 or character width or some other offset.
newX = 0; newX += characterWidth; if(newX + chracterWidth > boardWidth) newX=0; newY+= characterHeight;
That results in no overlap and having nothing to iterate or keep track of additional to what you do now, the only downside is the pattern of the displayed characters being 'checker board style' or right next to each other (with possible random spacing in between horizontal and vertical placement e.g. you could adjust the padding randomly if you wanted too)
It's the whole random thing in the first place that adds the complexity.
AND I updated your fiddle to prove I eliminated the random and stopped the overlap :)
http://jsfiddle.net/pUwKb/51/

HTML5 Canvas - how to zoom in the pixels?

How would one zoom in a Canvas to see the pixels? Currently when I try to use the scale() function the image is always antialiased.
The property mozImageSmoothingEnabled seems to work, but it's only for Firefox.
As far as I know any rescaling done by the browser will result in a smooth interpolation.
So as long as you want to do this with JS you will have to let JS do all the work. This means either finding a nice library or writing a function yourself. It could look like this. But I hope it's possible to make it faster. As it's one of the simplest scaling algorithms there are probably many people who thought up improvements to do it even faster.
function resize(ctx, sx, sy, sw, sh, tx, ty, tw, th) {
var source = ctx.getImageData(sx, sy, sw, sh);
var sdata = source.data;
var target = ctx.createImageData(tw, th);
var tdata = target.data;
var mapx = [];
var ratiox = sw / tw, px = 0;
for (var i = 0; i < tw; ++i) {
mapx[i] = 4 * Math.floor(px);
px += ratiox;
}
var mapy = [];
var ratioy = sh / th, py = 0;
for (var i = 0; i < th; ++i) {
mapy[i] = 4 * sw * Math.floor(py);
py += ratioy;
}
var tp = 0;
for (py = 0; py < th; ++py) {
for (px = 0; px < tw; ++px) {
var sp = mapx[px] + mapy[py];
tdata[tp++] = sdata[sp++];
tdata[tp++] = sdata[sp++];
tdata[tp++] = sdata[sp++];
tdata[tp++] = sdata[sp++];
}
}
ctx.putImageData(target, tx, ty);
}
This function would take the rectangle of size (sw,sh) at (sx,sy), resize it to (tw,th) and draw it at (tx,ty).
As far as I know the antialiasing behavior is not defined in the spec and will depend on the browser.
One thing you could try is if you set the canvas's width/height with CSS into for example 300x300 and then give the canvas width and height attributes of 150 and 150, it will appear "zoomed in" by 200%. I'm not sure whether this will trigger the antialiasing, but do give it a shot.

Categories