Anyone know of function that can break text at word boundaries to fit into rectangle
Following is code for rectangle and text
window.onload = function () {
var outsideRectX1=30, outsideRectY1=30,outsideRectX2=220, outsideRectY2=480, outsideRectR=10;
var group = paper.set();
var rect1=paper.rect(outsideRectX1+40, outsideRectY1+70, 80, 40,10);
var text3=paper.text(outsideRectX1+75, outsideRectY1+85,"Test code for wrap text").attr({fill: '#000000', 'font-family':'calibri', 'font-size':'14px'});
group.push(rect1);
group.push(text3);
};
When text is greater than rectangle width it automatically wrap so that it always display into rectangle boundaries.
I'm not sure whether there is any direct way to wrap the text according to the size of the rectangle. May be you can specify line breaks or a "\n". Or you can try to resize the rectangle as and when the text length increases.
Here is a sample code where the rectangle resize as the text length increases.
var recttext = paper.set();
el = paper.rect(0, 0, 300, 200);
text = paper.text(0,10, "Hi... This is a test to check whether the rectangle dynamically changes its size.").attr({"text-anchor":"start",fill:'#ff0000',"font-size": 14});
text1=paper.text(0,30,"hi").attr({"text-anchor":"start",fill: '#ff0000',"font-size": 14});
//el.setSize(495,200);
recttext.push(el);
recttext.push(text);
recttext.push(text1);
alert(recttext.getBBox().width);
alert(recttext.getBBox().height);
var att = {width:recttext.getBBox().width,height:recttext.getBBox().height};
el.attr(att);
recttext.translate(700,400);
I know it's a little belated now, but you might be interested in my [Raphael-paragraph][1] project.
It's a small library that allows you to create auto-wrapped multiline text with maximum width and height constraints, line height and text style configuration. It's still quite beta-ish and requires a lot of optimization, but it should work for your purposes.
Usage examples and documentation are provided on the GitHub page.
Related
In short, given a font (with size, weight, etc.) and a string, is there a way I extract an array of pixel coordinates relative to the top left of the first letter using JavaScript?
E.g. I might become
[
[0,0],
[0,1],
...
]
Edit: I am not looking for the bounding box, rather I am looking for the coordinates of each and every individual pixel that makes up the text. I need this information to essentially recreate the text later using squares.
Yes, you can use the canvas element to obtain text metrics:
// setup canvas
var c = document.createElement("canvas"),
ctx = c.getContext("2d");
// define (pre-loaded) font:
ctx.font = "bold 16px sans-serif";
// get metrics
var m = ctx.measureText("Hello");
The metrics object will give you the width and height etc. But - only width is currently supported in most browsers. There exists a poly-fill that will cover things like ascend and descend which you would need.
An alternative is to scan the bitmap to detect the rectangle the text coverts. I have given an answer here which covers this technique:
Javascript Method to detect area of a PNG that is not transparent
Also, if you only need the bounding box of the text (not pixel-accurate start point of the text itself) you can use a DOM element to get the width and height for that box. Here is one approach for that:
Use Javascript to get Maximum font size in canvas
Updated after clarification: For extracting pixels from the bitmap and convert those into points:
https://stackoverflow.com/a/30204783/1693593
I would like to know if there is any text direction on Phaser.js Text class
like when user input some text, then the text input in the canvas will have a text direction of right to left or left to right;
and I'm implementing this on whole canvas application
example in the normal html we can attain this using the css properties
direction:ltr,
direction:rtl
anyone has any idea on how to do it.
i was reading on the phaser.js text class but cannot find any properties to set the direction to right to left but no luck.
thanks in advance;
Since I can't find any documentation on the phaser to make this happen
then i simply just make a work around to look like i am able to make the direction
of the text to be right align.
Here is a simple text
var txt = this.game.add.text(10, 10, '0', {
font: "21px arial",
fill: "#00FF00",
align:'right',
fontWeight:'bold',
});
compute for the new position x of the txt
formula :
txt.x = contant - txt.width
the constant will be a reference point you want to offset
according to your positioning
so when the variable txt text updated
then you can re-position it again using
the the new data
txt.setText(100);
txt.x = 84 - (txt.width);
it looks like phaser text now supports rtl through this class:
Phaser.GameObjects. TextStyle
Try this:
yourApplication.canvas.setAttribute("dir", "rtl");
... where yourApplication holds the reference to your game/application. This adds an attribute to the DOM canvas element your game/application draws to (if that's what you're after).
I'm trying to measure the exact height used to render a given string with a given font with an SVG text tag.
I've tried using getBBox and getExtentOfChar, but the height returned by both of these includes some extra space above (and sometimes below) the actual text rendered.
http://upload.wikimedia.org/wikipedia/commons/3/39/Typography_Line_Terms.svg
Using the terms in this image, I'm trying to get the either the cap height + descender height of the text being rendered. Or, if that's not possible, just the cap height. Is there a good way to calculate these values?
Here's a quick codepen showing the extra space I'm talking about:
http://codepen.io/pcorey/pen/amkGl
HTML:
<div>
<svg><text>Hello</text></svg>
<svg><text>Age</text></svg>
</div>
JS:
$(function() {
$('svg').each(function() {
var svg = $(this);
var text = svg.find('text');
var bbox = text.get(0).getBBox();
svg.get(0).setAttribute('viewBox',
[bbox.x,
bbox.y,
bbox.width,
bbox.height].join(' '));
});
});
I understand that this is a fairly font-specific thing, so this might be totally impossible...
No. All the SVG DOM methods (getBBox(), getExtentOfChar()) are defined to return the full glyph cell height. That extra space above the cap height is allowance for taller glyphs - such as accented capitals. I think this is true for HTML DOM methods as well.
There are, however, JS libraries around which may be of use. For example:
https://github.com/Pomax/fontmetrics.js
I have not used this library myself, so I can't tell you how reliable or accurate it is.
Using Raphael JS 2.1.2, the following code:
var distance = 250;
var sizes = [ 14, 18, 24, 48, 72, 96 ];
for(var i = 0; i < sizes.length; i++)
{
var size = sizes[i];
var text = me.paper.text(distance + (size * 5), me.top + 200, size).attr({ 'font-size': size });
var rect = text.getBBox();
text.paper.rect(rect.x, rect.y, rect.width, rect.height).attr({ stroke: '#FF0000' });
}
produces this output:
How can I accurately measure the height of the text, as you can see the bounding box includes vertical padding which is relative to the font size?
Also $(text.node).height() returns the same value as rect.height. I am trying to align the top and/or bottom of text with other elements so I need some way to determine the padding or text height per font-size.
I could maintain a collection of { size: [font size], padding: [padding] }, but it would be good if I could generate this at runtime.
You can't. Actually this is not a "padding". getBBox returns dimentions given from a font metric, not individual glyphs. BBox height for text element includes font ascent and descent.
In most fonts, ascent reserves a gap above cap-height for glyphs such as "Ä". Discenders are reserved for lowercase characters with "tails" such as "g", "j", "q" and etc. For example, draw a rect around text "Äg".
For more detais see:
http://commons.oreilly.com/wiki/index.php/SVG_Essentials/Text
http://www.w3.org/TR/SVG11/text.html#BaselineAlignmentProperties
http://en.wikipedia.org/wiki/Baseline_(typography)
It's possible but it's messy. You can do this by using OpenType.js, then drawing a path using same text/size as Raphael with OpenType getPath and measuring the path. You can measure the outputted path with Raphael.pathBBox(path.toPathData()) or (preferable as its faster though more limited browser support) with creating a temp SVG as outlined here.
The size of the path will be the exact size of your text as you desired.
Along the same lines you may also encounter a position challenge i.e. trying to determine how the svg box fits over the raphael box. You can use the ascender/descender values provided by the font object returned from OpenType load alongside with the y/y2 values of your SVG path. All of these will allow you to figure out the baseline of OpenType text and you can match this to your Raphael box.
I'm trying to do something like:
$('<span>random text in here</span>').width()
But the width it's returning is 0. (The reason I'm trying to do this is to get the pixel width of a given text.)
How would I get this width, programmatically?
Thanks
You have to have it rendered.
You may do this :
var s = $('<span>random text in here</span>');
s.appendTo(document.body);
var w = s.width();
s.remove();
Demonstration
Note that :
nothing is displayed if you do this like I do in one go. For all practical purposes, nothing is inserted in the DOM,
you could also use an in memory canvas but it wouldn't handle anything more complex than simple text and wouldn't take into account your span's css settings.
Here's the solution measuring the width of some text using an in memory canvas :
var canvas = document.createElement('canvas');
var c = canvas.getContext('2d');
// set here c.font to adjust it to your need
var w = c.measureText('random text in here').width;
Demonstration
I would use the first one in the general case but it might depend on why you want to measure the text.