libraries/EaselJS_docs/files/easeljs_display_Text.js.html (view raw)
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="utf-8">
5 <link rel="stylesheet" href="../assets/css/yui-cssgrids-min.css">
6 <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
7 <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
8 <link rel="shortcut icon" type="image/x-icon" href="../assets/favicon.ico">
9 <script src="../assets/js/yui-source.js"></script>
10 <title>EaselJS v1.0.0 API Documentation : easeljs/display/Text.js</title>
11</head>
12<body class="yui3-skin-sam">
13
14<div id="doc">
15 <div id="hd" class="yui3-g header">
16 <div class="yui3-u-3-4">
17
18 <h1><a href="http://www.createjs.com/easeljs"><img src="../assets/docs-icon-EaselJS.png" title="EaselJS"></a></h1>
19
20 </div>
21 <div class="version">
22 <em>API Documentation for: 1.0.0</em>
23 </div>
24 </div>
25 <div id="bd" class="yui3-g">
26
27 <div class="yui3-u-1-4">
28 <div id="docs-sidebar" class="sidebar apidocs">
29 <div id="api-list">
30 <h2 class="off-left">APIs</h2>
31 <div id="api-tabview" class="tabview">
32 <ul class="tabs">
33 <li><a href="#api-classes">Classes</a></li>
34 </ul>
35
36 <div id="api-tabview-filter">
37 <input type="search" id="api-filter" placeholder="Type to filter APIs">
38 </div>
39
40 <div id="api-tabview-panel">
41 <ul id="api-classes" class="apis classes">
42
43 <li><a href="../classes/AlphaMapFilter.html">AlphaMapFilter</a></li>
44
45 <li><a href="../classes/AlphaMaskFilter.html">AlphaMaskFilter</a></li>
46
47 <li><a href="../classes/Bitmap.html">Bitmap</a></li>
48
49 <li><a href="../classes/BitmapCache.html">BitmapCache</a></li>
50
51 <li><a href="../classes/BitmapText.html">BitmapText</a></li>
52
53 <li><a href="../classes/BlurFilter.html">BlurFilter</a></li>
54
55 <li><a href="../classes/ButtonHelper.html">ButtonHelper</a></li>
56
57 <li><a href="../classes/ColorFilter.html">ColorFilter</a></li>
58
59 <li><a href="../classes/ColorMatrix.html">ColorMatrix</a></li>
60
61 <li><a href="../classes/ColorMatrixFilter.html">ColorMatrixFilter</a></li>
62
63 <li><a href="../classes/Container.html">Container</a></li>
64
65 <li><a href="../classes/DisplayObject.html">DisplayObject</a></li>
66
67 <li><a href="../classes/DisplayProps.html">DisplayProps</a></li>
68
69 <li><a href="../classes/DOMElement.html">DOMElement</a></li>
70
71 <li><a href="../classes/EaselJS.html">EaselJS</a></li>
72
73 <li><a href="../classes/Event.html">Event</a></li>
74
75 <li><a href="../classes/EventDispatcher.html">EventDispatcher</a></li>
76
77 <li><a href="../classes/Filter.html">Filter</a></li>
78
79 <li><a href="../classes/Graphics.html">Graphics</a></li>
80
81 <li><a href="../classes/Graphics.Arc.html">Graphics.Arc</a></li>
82
83 <li><a href="../classes/Graphics.ArcTo.html">Graphics.ArcTo</a></li>
84
85 <li><a href="../classes/Graphics.BeginPath.html">Graphics.BeginPath</a></li>
86
87 <li><a href="../classes/Graphics.BezierCurveTo.html">Graphics.BezierCurveTo</a></li>
88
89 <li><a href="../classes/Graphics.Circle.html">Graphics.Circle</a></li>
90
91 <li><a href="../classes/Graphics.ClosePath.html">Graphics.ClosePath</a></li>
92
93 <li><a href="../classes/Graphics.Ellipse.html">Graphics.Ellipse</a></li>
94
95 <li><a href="../classes/Graphics.Fill.html">Graphics.Fill</a></li>
96
97 <li><a href="../classes/Graphics.LineTo.html">Graphics.LineTo</a></li>
98
99 <li><a href="../classes/Graphics.MoveTo.html">Graphics.MoveTo</a></li>
100
101 <li><a href="../classes/Graphics.PolyStar.html">Graphics.PolyStar</a></li>
102
103 <li><a href="../classes/Graphics.QuadraticCurveTo.html">Graphics.QuadraticCurveTo</a></li>
104
105 <li><a href="../classes/Graphics.Rect.html">Graphics.Rect</a></li>
106
107 <li><a href="../classes/Graphics.RoundRect.html">Graphics.RoundRect</a></li>
108
109 <li><a href="../classes/Graphics.Stroke.html">Graphics.Stroke</a></li>
110
111 <li><a href="../classes/Graphics.StrokeDash.html">Graphics.StrokeDash</a></li>
112
113 <li><a href="../classes/Graphics.StrokeStyle.html">Graphics.StrokeStyle</a></li>
114
115 <li><a href="../classes/Matrix2D.html">Matrix2D</a></li>
116
117 <li><a href="../classes/MouseEvent.html">MouseEvent</a></li>
118
119 <li><a href="../classes/MovieClip.html">MovieClip</a></li>
120
121 <li><a href="../classes/MovieClipPlugin.html">MovieClipPlugin</a></li>
122
123 <li><a href="../classes/Point.html">Point</a></li>
124
125 <li><a href="../classes/Rectangle.html">Rectangle</a></li>
126
127 <li><a href="../classes/Shadow.html">Shadow</a></li>
128
129 <li><a href="../classes/Shape.html">Shape</a></li>
130
131 <li><a href="../classes/Sprite.html">Sprite</a></li>
132
133 <li><a href="../classes/SpriteSheet.html">SpriteSheet</a></li>
134
135 <li><a href="../classes/SpriteSheetBuilder.html">SpriteSheetBuilder</a></li>
136
137 <li><a href="../classes/SpriteSheetUtils.html">SpriteSheetUtils</a></li>
138
139 <li><a href="../classes/Stage.html">Stage</a></li>
140
141 <li><a href="../classes/StageGL.html">StageGL</a></li>
142
143 <li><a href="../classes/Text.html">Text</a></li>
144
145 <li><a href="../classes/Ticker.html">Ticker</a></li>
146
147 <li><a href="../classes/Touch.html">Touch</a></li>
148
149 <li><a href="../classes/UID.html">UID</a></li>
150
151 <li><a href="../classes/Utility Methods.html">Utility Methods</a></li>
152
153 <li><a href="../classes/VideoBuffer.html">VideoBuffer</a></li>
154
155 <li><a href="../classes/WebGLInspector.html">WebGLInspector</a></li>
156
157 </ul>
158
159 <ul id="api-modules" class="apis modules">
160
161 <li><a href="../modules/CreateJS.html">CreateJS</a></li>
162
163 <li><a href="../modules/EaselJS.html">EaselJS</a></li>
164
165 </ul>
166 </div>
167 </div>
168</div>
169
170 </div>
171 </div>
172 <div class="yui3-u-3-4">
173 <div id="api-options">
174 Show:
175 <label for="api-show-inherited">
176 <input type="checkbox" id="api-show-inherited" checked>
177 Inherited
178 </label>
179
180 <label for="api-show-protected">
181 <input type="checkbox" id="api-show-protected">
182 Protected
183 </label>
184
185 <label for="api-show-private">
186 <input type="checkbox" id="api-show-private">
187 Private
188 </label>
189 <label for="api-show-deprecated">
190 <input type="checkbox" id="api-show-deprecated">
191 Deprecated
192 </label>
193
194 </div>
195 <div class="apidocs">
196 <div id="docs-main">
197 <div class="content source-content">
198 <script>
199 var name = easeljs/display/Text.js
200</script>
201<h1 class="file-heading">File:Text.js</h1>
202
203<div class="file">
204 <pre class="code prettyprint linenums">
205/*
206* Text
207* Visit http://createjs.com/ for documentation, updates and examples.
208*
209* Copyright (c) 2010 gskinner.com, inc.
210*
211* Permission is hereby granted, free of charge, to any person
212* obtaining a copy of this software and associated documentation
213* files (the "Software"), to deal in the Software without
214* restriction, including without limitation the rights to use,
215* copy, modify, merge, publish, distribute, sublicense, and/or sell
216* copies of the Software, and to permit persons to whom the
217* Software is furnished to do so, subject to the following
218* conditions:
219*
220* The above copyright notice and this permission notice shall be
221* included in all copies or substantial portions of the Software.
222*
223* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
224* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
225* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
226* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
227* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
228* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
229* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
230* OTHER DEALINGS IN THE SOFTWARE.
231*/
232
233/**
234 * @module EaselJS
235 */
236
237// namespace:
238this.createjs = this.createjs||{};
239
240(function() {
241 "use strict";
242
243
244// constructor:
245 /**
246 * Display one or more lines of dynamic text (not user editable) in the display list. Line wrapping support (using the
247 * lineWidth) is very basic, wrapping on spaces and tabs only. Note that as an alternative to Text, you can position HTML
248 * text above or below the canvas relative to items in the display list using the {{#crossLink "DisplayObject/localToGlobal"}}{{/crossLink}}
249 * method, or using {{#crossLink "DOMElement"}}{{/crossLink}}.
250 *
251 * <b>Please note that Text does not support HTML text, and can only display one font style at a time.</b> To use
252 * multiple font styles, you will need to create multiple text instances, and position them manually.
253 *
254 * <h4>Example</h4>
255 *
256 * var text = new createjs.Text("Hello World", "20px Arial", "#ff7700");
257 * text.x = 100;
258 * text.textBaseline = "alphabetic";
259 *
260 * CreateJS Text supports web fonts (the same rules as Canvas). The font must be loaded and supported by the browser
261 * before it can be displayed.
262 *
263 * <strong>Note:</strong> Text can be expensive to generate, so cache instances where possible. Be aware that not all
264 * browsers will render Text exactly the same.
265 * @class Text
266 * @extends DisplayObject
267 * @constructor
268 * @param {String} [text] The text to display.
269 * @param {String} [font] The font style to use. Any valid value for the CSS font attribute is acceptable (ex. "bold
270 * 36px Arial").
271 * @param {String} [color] The color to draw the text in. Any valid value for the CSS color attribute is acceptable (ex.
272 * "#F00", "red", or "#FF0000").
273 **/
274 function Text(text, font, color) {
275 this.DisplayObject_constructor();
276
277
278 // public properties:
279 /**
280 * The text to display.
281 * @property text
282 * @type String
283 **/
284 this.text = text;
285
286 /**
287 * The font style to use. Any valid value for the CSS font attribute is acceptable (ex. "bold 36px Arial").
288 * @property font
289 * @type String
290 **/
291 this.font = font;
292
293 /**
294 * The color to draw the text in. Any valid value for the CSS color attribute is acceptable (ex. "#F00"). Default is "#000".
295 * It will also accept valid canvas fillStyle values.
296 * @property color
297 * @type String
298 **/
299 this.color = color;
300
301 /**
302 * The horizontal text alignment. Any of "start", "end", "left", "right", and "center". For detailed
303 * information view the
304 * <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#text-styles">
305 * whatwg spec</a>. Default is "left".
306 * @property textAlign
307 * @type String
308 **/
309 this.textAlign = "left";
310
311 /**
312 * The vertical alignment point on the font. Any of "top", "hanging", "middle", "alphabetic", "ideographic", or
313 * "bottom". For detailed information view the <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#text-styles">
314 * whatwg spec</a>. Default is "top".
315 * @property textBaseline
316 * @type String
317 */
318 this.textBaseline = "top";
319
320 /**
321 * The maximum width to draw the text. If maxWidth is specified (not null), the text will be condensed or
322 * shrunk to make it fit in this width. For detailed information view the
323 * <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#text-styles">
324 * whatwg spec</a>.
325 * @property maxWidth
326 * @type Number
327 */
328 this.maxWidth = null;
329
330 /**
331 * If greater than 0, the text will be drawn as a stroke (outline) of the specified width.
332 * @property outline
333 * @type Number
334 **/
335 this.outline = 0;
336
337 /**
338 * Indicates the line height (vertical distance between baselines) for multi-line text. If null or 0,
339 * the value of getMeasuredLineHeight is used.
340 * @property lineHeight
341 * @type Number
342 **/
343 this.lineHeight = 0;
344
345 /**
346 * Indicates the maximum width for a line of text before it is wrapped to multiple lines. If null,
347 * the text will not be wrapped.
348 * @property lineWidth
349 * @type Number
350 **/
351 this.lineWidth = null;
352 }
353 var p = createjs.extend(Text, createjs.DisplayObject);
354
355 // TODO: deprecated
356 // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details.
357
358
359// static properties:
360 /**
361 * @property _workingContext
362 * @type CanvasRenderingContext2D
363 * @private
364 **/
365 var canvas = (createjs.createCanvas?createjs.createCanvas():document.createElement("canvas"));
366 if (canvas.getContext) { Text._workingContext = canvas.getContext("2d"); canvas.width = canvas.height = 1; }
367
368
369// constants:
370 /**
371 * Lookup table for the ratio to offset bounds x calculations based on the textAlign property.
372 * @property H_OFFSETS
373 * @type Object
374 * @protected
375 * @static
376 **/
377 Text.H_OFFSETS = {start: 0, left: 0, center: -0.5, end: -1, right: -1};
378
379 /**
380 * Lookup table for the ratio to offset bounds y calculations based on the textBaseline property.
381 * @property H_OFFSETS
382 * @type Object
383 * @protected
384 * @static
385 **/
386 Text.V_OFFSETS = {top: 0, hanging: -0.01, middle: -0.4, alphabetic: -0.8, ideographic: -0.85, bottom: -1};
387
388
389// public methods:
390 /**
391 * Returns true or false indicating whether the display object would be visible if drawn to a canvas.
392 * This does not account for whether it would be visible within the boundaries of the stage.
393 * NOTE: This method is mainly for internal use, though it may be useful for advanced uses.
394 * @method isVisible
395 * @return {Boolean} Whether the display object would be visible if drawn to a canvas
396 **/
397 p.isVisible = function() {
398 var hasContent = this.cacheCanvas || (this.text != null && this.text !== "");
399 return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0 && hasContent);
400 };
401
402 /**
403 * Draws the Text into the specified context ignoring its visible, alpha, shadow, and transform.
404 * Returns true if the draw was handled (useful for overriding functionality).
405 * NOTE: This method is mainly for internal use, though it may be useful for advanced uses.
406 * @method draw
407 * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into.
408 * @param {Boolean} ignoreCache Indicates whether the draw operation should ignore any current cache.
409 * For example, used for drawing the cache (to prevent it from simply drawing an existing cache back
410 * into itself).
411 **/
412 p.draw = function(ctx, ignoreCache) {
413 if (this.DisplayObject_draw(ctx, ignoreCache)) { return true; }
414
415 var col = this.color || "#000";
416 if (this.outline) { ctx.strokeStyle = col; ctx.lineWidth = this.outline*1; }
417 else { ctx.fillStyle = col; }
418
419 this._drawText(this._prepContext(ctx));
420 return true;
421 };
422
423 /**
424 * Returns the measured, untransformed width of the text without wrapping. Use getBounds for a more robust value.
425 * @method getMeasuredWidth
426 * @return {Number} The measured, untransformed width of the text.
427 **/
428 p.getMeasuredWidth = function() {
429 return this._getMeasuredWidth(this.text);
430 };
431
432 /**
433 * Returns an approximate line height of the text, ignoring the lineHeight property. This is based on the measured
434 * width of a "M" character multiplied by 1.2, which provides an approximate line height for most fonts.
435 * @method getMeasuredLineHeight
436 * @return {Number} an approximate line height of the text, ignoring the lineHeight property. This is
437 * based on the measured width of a "M" character multiplied by 1.2, which approximates em for most fonts.
438 **/
439 p.getMeasuredLineHeight = function() {
440 return this._getMeasuredWidth("M")*1.2;
441 };
442
443 /**
444 * Returns the approximate height of multi-line text by multiplying the number of lines against either the
445 * <code>lineHeight</code> (if specified) or {{#crossLink "Text/getMeasuredLineHeight"}}{{/crossLink}}. Note that
446 * this operation requires the text flowing logic to run, which has an associated CPU cost.
447 * @method getMeasuredHeight
448 * @return {Number} The approximate height of the untransformed multi-line text.
449 **/
450 p.getMeasuredHeight = function() {
451 return this._drawText(null,{}).height;
452 };
453
454 /**
455 * Docced in superclass.
456 */
457 p.getBounds = function() {
458 var rect = this.DisplayObject_getBounds();
459 if (rect) { return rect; }
460 if (this.text == null || this.text === "") { return null; }
461 var o = this._drawText(null, {});
462 var w = (this.maxWidth && this.maxWidth < o.width) ? this.maxWidth : o.width;
463 var x = w * Text.H_OFFSETS[this.textAlign||"left"];
464 var lineHeight = this.lineHeight||this.getMeasuredLineHeight();
465 var y = lineHeight * Text.V_OFFSETS[this.textBaseline||"top"];
466 return this._rectangle.setValues(x, y, w, o.height);
467 };
468
469 /**
470 * Returns an object with width, height, and lines properties. The width and height are the visual width and height
471 * of the drawn text. The lines property contains an array of strings, one for
472 * each line of text that will be drawn, accounting for line breaks and wrapping. These strings have trailing
473 * whitespace removed.
474 * @method getMetrics
475 * @return {Object} An object with width, height, and lines properties.
476 **/
477 p.getMetrics = function() {
478 var o = {lines:[]};
479 o.lineHeight = this.lineHeight || this.getMeasuredLineHeight();
480 o.vOffset = o.lineHeight * Text.V_OFFSETS[this.textBaseline||"top"];
481 return this._drawText(null, o, o.lines);
482 };
483
484 /**
485 * Returns a clone of the Text instance.
486 * @method clone
487 * @return {Text} a clone of the Text instance.
488 **/
489 p.clone = function() {
490 return this._cloneProps(new Text(this.text, this.font, this.color));
491 };
492
493 /**
494 * Returns a string representation of this object.
495 * @method toString
496 * @return {String} a string representation of the instance.
497 **/
498 p.toString = function() {
499 return "[Text (text="+ (this.text.length > 20 ? this.text.substr(0, 17)+"..." : this.text) +")]";
500 };
501
502
503// private methods:
504 /**
505 * @method _cloneProps
506 * @param {Text} o
507 * @protected
508 * @return {Text} o
509 **/
510 p._cloneProps = function(o) {
511 this.DisplayObject__cloneProps(o);
512 o.textAlign = this.textAlign;
513 o.textBaseline = this.textBaseline;
514 o.maxWidth = this.maxWidth;
515 o.outline = this.outline;
516 o.lineHeight = this.lineHeight;
517 o.lineWidth = this.lineWidth;
518 return o;
519 };
520
521 /**
522 * @method _getWorkingContext
523 * @param {CanvasRenderingContext2D} ctx
524 * @return {CanvasRenderingContext2D}
525 * @protected
526 **/
527 p._prepContext = function(ctx) {
528 ctx.font = this.font||"10px sans-serif";
529 ctx.textAlign = this.textAlign||"left";
530 ctx.textBaseline = this.textBaseline||"top";
531 ctx.lineJoin = "miter";
532 ctx.miterLimit = 2.5;
533 return ctx;
534 };
535
536 /**
537 * Draws multiline text.
538 * @method _drawText
539 * @param {CanvasRenderingContext2D} ctx
540 * @param {Object} o
541 * @param {Array} lines
542 * @return {Object}
543 * @protected
544 **/
545 p._drawText = function(ctx, o, lines) {
546 var paint = !!ctx;
547 if (!paint) {
548 ctx = Text._workingContext;
549 ctx.save();
550 this._prepContext(ctx);
551 }
552 var lineHeight = this.lineHeight||this.getMeasuredLineHeight();
553
554 var maxW = 0, count = 0;
555 var hardLines = String(this.text).split(/(?:\r\n|\r|\n)/);
556 for (var i=0, l=hardLines.length; i<l; i++) {
557 var str = hardLines[i];
558 var w = null;
559
560 if (this.lineWidth != null && (w = ctx.measureText(str).width) > this.lineWidth) {
561 // text wrapping:
562 var words = str.split(/(\s)/);
563 str = words[0];
564 w = ctx.measureText(str).width;
565
566 for (var j=1, jl=words.length; j<jl; j+=2) {
567 // Line needs to wrap:
568 var wordW = ctx.measureText(words[j] + words[j+1]).width;
569 if (w + wordW > this.lineWidth) {
570 if (paint) { this._drawTextLine(ctx, str, count*lineHeight); }
571 if (lines) { lines.push(str); }
572 if (w > maxW) { maxW = w; }
573 str = words[j+1];
574 w = ctx.measureText(str).width;
575 count++;
576 } else {
577 str += words[j] + words[j+1];
578 w += wordW;
579 }
580 }
581 }
582
583 if (paint) { this._drawTextLine(ctx, str, count*lineHeight); }
584 if (lines) { lines.push(str); }
585 if (o && w == null) { w = ctx.measureText(str).width; }
586 if (w > maxW) { maxW = w; }
587 count++;
588 }
589
590 if (o) {
591 o.width = maxW;
592 o.height = count*lineHeight;
593 }
594 if (!paint) { ctx.restore(); }
595 return o;
596 };
597
598 /**
599 * @method _drawTextLine
600 * @param {CanvasRenderingContext2D} ctx
601 * @param {String} text
602 * @param {Number} y
603 * @protected
604 **/
605 p._drawTextLine = function(ctx, text, y) {
606 // Chrome 17 will fail to draw the text if the last param is included but null, so we feed it a large value instead:
607 if (this.outline) { ctx.strokeText(text, 0, y, this.maxWidth||0xFFFF); }
608 else { ctx.fillText(text, 0, y, this.maxWidth||0xFFFF); }
609 };
610
611
612 /**
613 * @method _getMeasuredWidth
614 * @param {String} text
615 * @protected
616 **/
617 p._getMeasuredWidth = function(text) {
618 var ctx = Text._workingContext;
619 ctx.save();
620 var w = this._prepContext(ctx).measureText(text).width;
621 ctx.restore();
622 return w;
623 };
624
625
626 createjs.Text = createjs.promote(Text, "DisplayObject");
627}());
628
629 </pre>
630</div>
631
632 </div>
633 </div>
634 </div>
635 </div>
636 </div>
637</div>
638<script src="../assets/vendor/prettify/prettify-min.js"></script>
639<script>prettyPrint();</script>
640<script src="../assets/js/yui-prettify.js"></script>
641<script src="../assets/../api.js"></script>
642<script src="../assets/js/api-filter.js"></script>
643<script src="../assets/js/api-list.js"></script>
644<script src="../assets/js/api-search.js"></script>
645<script src="../assets/js/apidocs.js"></script>
646</body>
647</html>