Debian Codegraph @

closure-library/closure/goog/graphics/canvasgraphics.js

raw
1 // Copyright 2007 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15
16 /**
17 * @fileoverview CanvasGraphics sub class that uses the canvas tag for drawing.
18 * @author [email protected] (Robby Walker)
19 */
20
21
22 goog.provide('goog.graphics.CanvasGraphics');
23
24
25 goog.require('goog.dom.TagName');
26 goog.require('goog.events.EventType');
27 goog.require('goog.graphics.AbstractGraphics');
28 goog.require('goog.graphics.CanvasEllipseElement');
29 goog.require('goog.graphics.CanvasGroupElement');
30 goog.require('goog.graphics.CanvasImageElement');
31 goog.require('goog.graphics.CanvasPathElement');
32 goog.require('goog.graphics.CanvasRectElement');
33 goog.require('goog.graphics.CanvasTextElement');
34 goog.require('goog.graphics.Font');
35 goog.require('goog.graphics.SolidFill');
36 goog.require('goog.math.Size');
37 goog.require('goog.style');
38
39
40
41 /**
42 * A Graphics implementation for drawing using canvas.
43 * @param {string|number} width The (non-zero) width in pixels. Strings
44 * expressing percentages of parent with (e.g. '80%') are also accepted.
45 * @param {string|number} height The (non-zero) height in pixels. Strings
46 * expressing percentages of parent with (e.g. '80%') are also accepted.
47 * @param {?number=} opt_coordWidth The coordinate width - if
48 * omitted or null, defaults to same as width.
49 * @param {?number=} opt_coordHeight The coordinate height - if
50 * omitted or null, defaults to same as height.
51 * @param {goog.dom.DomHelper=} opt_domHelper The DOM helper object for the
52 * document we want to render in.
53 * @constructor
54 * @extends {goog.graphics.AbstractGraphics}
55 * @deprecated goog.graphics is deprecated. It existed to abstract over browser
56 * differences before the canvas tag was widely supported. See
57 * http://en.wikipedia.org/wiki/Canvas_element for details.
58 */
59 goog.graphics.CanvasGraphics = function(
60 width, height, opt_coordWidth, opt_coordHeight, opt_domHelper) {
61 goog.graphics.AbstractGraphics.call(
62 this, width, height, opt_coordWidth, opt_coordHeight, opt_domHelper);
63 };
64 goog.inherits(goog.graphics.CanvasGraphics, goog.graphics.AbstractGraphics);
65
66
67 /**
68 * Sets the fill for the given element.
69 * @param {goog.graphics.StrokeAndFillElement} element The element
70 * wrapper.
71 * @param {goog.graphics.Fill} fill The fill object.
72 * @override
73 */
74 goog.graphics.CanvasGraphics.prototype.setElementFill = function(
75 element, fill) {
76 this.redraw();
77 };
78
79
80 /**
81 * Sets the stroke for the given element.
82 * @param {goog.graphics.StrokeAndFillElement} element The element
83 * wrapper.
84 * @param {goog.graphics.Stroke} stroke The stroke object.
85 * @override
86 */
87 goog.graphics.CanvasGraphics.prototype.setElementStroke = function(
88 element, stroke) {
89 this.redraw();
90 };
91
92
93 /**
94 * Set the translation and rotation of an element.
95 *
96 * If a more general affine transform is needed than this provides
97 * (e.g. skew and scale) then use setElementAffineTransform.
98 * @param {goog.graphics.Element} element The element wrapper.
99 * @param {number} x The x coordinate of the translation transform.
100 * @param {number} y The y coordinate of the translation transform.
101 * @param {number} angle The angle of the rotation transform.
102 * @param {number} centerX The horizontal center of the rotation transform.
103 * @param {number} centerY The vertical center of the rotation transform.
104 * @override
105 */
106 goog.graphics.CanvasGraphics.prototype.setElementTransform = function(
107 element, x, y, angle, centerX, centerY) {
108 this.redraw();
109 };
110
111
112 /**
113 * Set the transformation of an element.
114 *
115 * Note that in this implementation this method just calls this.redraw()
116 * and the affineTransform param is unused.
117 * @param {!goog.graphics.Element} element The element wrapper.
118 * @param {!goog.graphics.AffineTransform} affineTransform The
119 * transformation applied to this element.
120 * @override
121 */
122 goog.graphics.CanvasGraphics.prototype.setElementAffineTransform = function(
123 element, affineTransform) {
124 this.redraw();
125 };
126
127
128 /**
129 * Push an element transform on to the transform stack.
130 * @param {goog.graphics.Element} element The transformed element.
131 */
132 goog.graphics.CanvasGraphics.prototype.pushElementTransform = function(
133 element) {
134 var ctx = this.getContext();
135 ctx.save();
136
137 var transform = element.getTransform();
138
139 // TODO(robbyw): Test for unsupported transforms i.e. skews.
140 var tx = transform.getTranslateX();
141 var ty = transform.getTranslateY();
142 if (tx || ty) {
143 ctx.translate(tx, ty);
144 }
145
146 var sinTheta = transform.getShearY();
147 if (sinTheta) {
148 ctx.rotate(Math.asin(sinTheta));
149 }
150 };
151
152
153 /**
154 * Pop an element transform off of the transform stack.
155 */
156 goog.graphics.CanvasGraphics.prototype.popElementTransform = function() {
157 this.getContext().restore();
158 };
159
160
161 /**
162 * Creates the DOM representation of the graphics area.
163 * @override
164 */
165 goog.graphics.CanvasGraphics.prototype.createDom = function() {
166 var element = this.dom_.createDom(
167 goog.dom.TagName.DIV, {'style': 'position:relative;overflow:hidden'});
168 this.setElementInternal(element);
169
170 this.canvas_ = this.dom_.createDom(goog.dom.TagName.CANVAS);
171 element.appendChild(this.canvas_);
172
173 /**
174 * The main canvas element.
175 * @type {goog.graphics.CanvasGroupElement}
176 */
177 this.canvasElement = new goog.graphics.CanvasGroupElement(this);
178
179 this.lastGroup_ = this.canvasElement;
180 this.redrawTimeout_ = 0;
181
182 this.updateSize();
183 };
184
185
186 /**
187 * Clears the drawing context object in response to actions that make the old
188 * context invalid - namely resize of the canvas element.
189 * @private
190 */
191 goog.graphics.CanvasGraphics.prototype.clearContext_ = function() {
192 this.context_ = null;
193 };
194
195
196 /**
197 * Returns the drawing context.
198 * @return {Object} The canvas element rendering context.
199 */
200 goog.graphics.CanvasGraphics.prototype.getContext = function() {
201 if (!this.getElement()) {
202 this.createDom();
203 }
204 if (!this.context_) {
205 this.context_ = this.canvas_.getContext('2d');
206 this.context_.save();
207 }
208 return this.context_;
209 };
210
211
212 /**
213 * Changes the coordinate system position.
214 * @param {number} left The coordinate system left bound.
215 * @param {number} top The coordinate system top bound.
216 * @override
217 */
218 goog.graphics.CanvasGraphics.prototype.setCoordOrigin = function(left, top) {
219 this.coordLeft = left;
220 this.coordTop = top;
221 this.redraw();
222 };
223
224
225 /**
226 * Changes the coordinate size.
227 * @param {number} coordWidth The coordinate width.
228 * @param {number} coordHeight The coordinate height.
229 * @override
230 */
231 goog.graphics.CanvasGraphics.prototype.setCoordSize = function(
232 coordWidth, coordHeight) {
233 goog.graphics.CanvasGraphics.superClass_.setCoordSize.apply(this, arguments);
234 this.redraw();
235 };
236
237
238 /**
239 * Change the size of the canvas.
240 * @param {number} pixelWidth The width in pixels.
241 * @param {number} pixelHeight The height in pixels.
242 * @override
243 */
244 goog.graphics.CanvasGraphics.prototype.setSize = function(
245 pixelWidth, pixelHeight) {
246 this.width = pixelWidth;
247 this.height = pixelHeight;
248
249 this.updateSize();
250 this.redraw();
251 };
252
253
254 /** @override */
255 goog.graphics.CanvasGraphics.prototype.getPixelSize = function() {
256 // goog.style.getSize does not work for Canvas elements. We
257 // have to compute the size manually if it is percentage based.
258 var width = this.width;
259 var height = this.height;
260 var computeWidth = goog.isString(width) && width.indexOf('%') != -1;
261 var computeHeight = goog.isString(height) && height.indexOf('%') != -1;
262
263 if (!this.isInDocument() && (computeWidth || computeHeight)) {
264 return null;
265 }
266
267 var parent;
268 var parentSize;
269
270 if (computeWidth) {
271 parent = /** @type {Element} */ (this.getElement().parentNode);
272 parentSize = goog.style.getSize(parent);
273 width = parseFloat(/** @type {string} */ (width)) * parentSize.width / 100;
274 }
275
276 if (computeHeight) {
277 parent = parent || /** @type {Element} */ (this.getElement().parentNode);
278 parentSize = parentSize || goog.style.getSize(parent);
279 height =
280 parseFloat(/** @type {string} */ (height)) * parentSize.height / 100;
281 }
282
283 return new goog.math.Size(
284 /** @type {number} */ (width),
285 /** @type {number} */ (height));
286 };
287
288
289 /**
290 * Update the size of the canvas.
291 */
292 goog.graphics.CanvasGraphics.prototype.updateSize = function() {
293 goog.style.setSize(this.getElement(), this.width, this.height);
294
295 var pixels = this.getPixelSize();
296 if (pixels) {
297 goog.style.setSize(
298 this.canvas_,
299 /** @type {number} */ (pixels.width),
300 /** @type {number} */ (pixels.height));
301 this.canvas_.width = pixels.width;
302 this.canvas_.height = pixels.height;
303 this.clearContext_();
304 }
305 };
306
307
308 /**
309 * Reset the canvas.
310 */
311 goog.graphics.CanvasGraphics.prototype.reset = function() {
312 var ctx = this.getContext();
313 ctx.restore();
314 var size = this.getPixelSize();
315 if (size.width && size.height) {
316 ctx.clearRect(0, 0, size.width, size.height);
317 }
318 ctx.save();
319 };
320
321
322 /**
323 * Remove all drawing elements from the graphics.
324 * @override
325 */
326 goog.graphics.CanvasGraphics.prototype.clear = function() {
327 this.reset();
328 this.canvasElement.clear();
329 var el = this.getElement();
330
331 // Remove all children (text nodes) except the canvas (which is at index 0)
332 while (el.childNodes.length > 1) {
333 el.removeChild(el.lastChild);
334 }
335 };
336
337
338 /**
339 * Redraw the entire canvas.
340 */
341 goog.graphics.CanvasGraphics.prototype.redraw = function() {
342 if (this.preventRedraw_) {
343 this.needsRedraw_ = true;
344 return;
345 }
346
347 if (this.isInDocument()) {
348 this.reset();
349
350 if (this.coordWidth) {
351 var pixels = this.getPixelSize();
352 this.getContext().scale(
353 pixels.width / this.coordWidth, pixels.height / this.coordHeight);
354 }
355 if (this.coordLeft || this.coordTop) {
356 this.getContext().translate(-this.coordLeft, -this.coordTop);
357 }
358 this.pushElementTransform(this.canvasElement);
359 this.canvasElement.draw(this.context_);
360 this.popElementTransform();
361 }
362 };
363
364
365 /**
366 * Draw an element, including any stroke or fill.
367 * @param {goog.graphics.Element} element The element to draw.
368 */
369 goog.graphics.CanvasGraphics.prototype.drawElement = function(element) {
370 if (element instanceof goog.graphics.CanvasTextElement) {
371 // Don't draw text since that is not implemented using canvas.
372 return;
373 }
374
375 var ctx = this.getContext();
376 this.pushElementTransform(element);
377
378 if (!element.getFill || !element.getStroke) {
379 // Draw without stroke or fill (e.g. the element is an image or group).
380 element.draw(ctx);
381 this.popElementTransform();
382 return;
383 }
384
385 var fill = element.getFill();
386 if (fill) {
387 if (fill instanceof goog.graphics.SolidFill) {
388 if (fill.getOpacity() != 0) {
389 ctx.globalAlpha = fill.getOpacity();
390 ctx.fillStyle = fill.getColor();
391 element.draw(ctx);
392 ctx.fill();
393 ctx.globalAlpha = 1;
394 }
395 } else { // (fill instanceof goog.graphics.LinearGradient)
396 var linearGradient = ctx.createLinearGradient(
397 fill.getX1(), fill.getY1(), fill.getX2(), fill.getY2());
398 linearGradient.addColorStop(0.0, fill.getColor1());
399 linearGradient.addColorStop(1.0, fill.getColor2());
400
401 ctx.fillStyle = linearGradient;
402 element.draw(ctx);
403 ctx.fill();
404 }
405 }
406
407 var stroke = element.getStroke();
408 if (stroke) {
409 element.draw(ctx);
410 ctx.strokeStyle = stroke.getColor();
411
412 var width = stroke.getWidth();
413 if (goog.isString(width) && width.indexOf('px') != -1) {
414 width = parseFloat(width) / this.getPixelScaleX();
415 }
416 ctx.lineWidth = width;
417
418 ctx.stroke();
419 }
420
421 this.popElementTransform();
422 };
423
424
425 /**
426 * Append an element.
427 *
428 * @param {goog.graphics.Element} element The element to draw.
429 * @param {goog.graphics.GroupElement|undefined} group The group to draw
430 * it in. If null or undefined, defaults to the root group.
431 * @protected
432 */
433 goog.graphics.CanvasGraphics.prototype.append = function(element, group) {
434 group = group || this.canvasElement;
435 group.appendChild(element);
436
437 if (this.isDrawable(group)) {
438 this.drawElement(element);
439 }
440 };
441
442
443 /**
444 * Draw an ellipse.
445 *
446 * @param {number} cx Center X coordinate.
447 * @param {number} cy Center Y coordinate.
448 * @param {number} rx Radius length for the x-axis.
449 * @param {number} ry Radius length for the y-axis.
450 * @param {goog.graphics.Stroke} stroke Stroke object describing the
451 * stroke.
452 * @param {goog.graphics.Fill} fill Fill object describing the fill.
453 * @param {goog.graphics.GroupElement=} opt_group The group wrapper
454 * element to append to. If not specified, appends to the main canvas.
455 *
456 * @return {!goog.graphics.EllipseElement} The newly created element.
457 * @override
458 */
459 goog.graphics.CanvasGraphics.prototype.drawEllipse = function(
460 cx, cy, rx, ry, stroke, fill, opt_group) {
461 var element = new goog.graphics.CanvasEllipseElement(
462 null, this, cx, cy, rx, ry, stroke, fill);
463 this.append(element, opt_group);
464 return element;
465 };
466
467
468 /**
469 * Draw a rectangle.
470 *
471 * @param {number} x X coordinate (left).
472 * @param {number} y Y coordinate (top).
473 * @param {number} width Width of rectangle.
474 * @param {number} height Height of rectangle.
475 * @param {goog.graphics.Stroke} stroke Stroke object describing the
476 * stroke.
477 * @param {goog.graphics.Fill} fill Fill object describing the fill.
478 * @param {goog.graphics.GroupElement=} opt_group The group wrapper
479 * element to append to. If not specified, appends to the main canvas.
480 *
481 * @return {!goog.graphics.RectElement} The newly created element.
482 * @override
483 */
484 goog.graphics.CanvasGraphics.prototype.drawRect = function(
485 x, y, width, height, stroke, fill, opt_group) {
486 var element = new goog.graphics.CanvasRectElement(
487 null, this, x, y, width, height, stroke, fill);
488 this.append(element, opt_group);
489 return element;
490 };
491
492
493 /**
494 * Draw an image.
495 *
496 * @param {number} x X coordinate (left).
497 * @param {number} y Y coordinate (top).
498 * @param {number} width Width of image.
499 * @param {number} height Height of image.
500 * @param {string} src Source of the image.
501 * @param {goog.graphics.GroupElement=} opt_group The group wrapper
502 * element to append to. If not specified, appends to the main canvas.
503 *
504 * @return {!goog.graphics.ImageElement} The newly created element.
505 */
506 goog.graphics.CanvasGraphics.prototype.drawImage = function(
507 x, y, width, height, src, opt_group) {
508 var element = new goog.graphics.CanvasImageElement(
509 null, this, x, y, width, height, src);
510 this.append(element, opt_group);
511 return element;
512 };
513
514
515 /**
516 * Draw a text string vertically centered on a given line.
517 *
518 * @param {string} text The text to draw.
519 * @param {number} x1 X coordinate of start of line.
520 * @param {number} y1 Y coordinate of start of line.
521 * @param {number} x2 X coordinate of end of line.
522 * @param {number} y2 Y coordinate of end of line.
523 * @param {?string} align Horizontal alignment: left (default), center, right.
524 * @param {goog.graphics.Font} font Font describing the font properties.
525 * @param {goog.graphics.Stroke} stroke Stroke object describing the stroke.
526 * @param {goog.graphics.Fill} fill Fill object describing the fill.
527 * @param {goog.graphics.GroupElement=} opt_group The group wrapper
528 * element to append to. If not specified, appends to the main canvas.
529 *
530 * @return {!goog.graphics.TextElement} The newly created element.
531 * @override
532 */
533 goog.graphics.CanvasGraphics.prototype.drawTextOnLine = function(
534 text, x1, y1, x2, y2, align, font, stroke, fill, opt_group) {
535 var element = new goog.graphics.CanvasTextElement(
536 this, text, x1, y1, x2, y2, align,
537 /** @type {!goog.graphics.Font} */ (font), stroke, fill);
538 this.append(element, opt_group);
539 return element;
540 };
541
542
543 /**
544 * Draw a path.
545 * @param {!goog.graphics.Path} path The path object to draw.
546 * @param {goog.graphics.Stroke} stroke Stroke object describing the stroke.
547 * @param {goog.graphics.Fill} fill Fill object describing the fill.
548 * @param {goog.graphics.GroupElement=} opt_group The group wrapper
549 * element to append to. If not specified, appends to the main canvas.
550 *
551 * @return {!goog.graphics.PathElement} The newly created element.
552 * @override
553 */
554 goog.graphics.CanvasGraphics.prototype.drawPath = function(
555 path, stroke, fill, opt_group) {
556 var element =
557 new goog.graphics.CanvasPathElement(null, this, path, stroke, fill);
558 this.append(element, opt_group);
559 return element;
560 };
561
562
563 /**
564 * @param {goog.graphics.GroupElement} group The group to possibly
565 * draw to.
566 * @return {boolean} Whether drawing can occur now.
567 */
568 goog.graphics.CanvasGraphics.prototype.isDrawable = function(group) {
569 return this.isInDocument() && !this.redrawTimeout_ &&
570 !this.isRedrawRequired(group);
571 };
572
573
574 /**
575 * Returns true if drawing to the given group means a redraw is required.
576 * @param {goog.graphics.GroupElement} group The group to draw to.
577 * @return {boolean} Whether drawing to this group should force a redraw.
578 */
579 goog.graphics.CanvasGraphics.prototype.isRedrawRequired = function(group) {
580 // TODO(robbyw): Moving up to any parent of lastGroup should not force redraw.
581 return group != this.canvasElement && group != this.lastGroup_;
582 };
583
584
585 /**
586 * Create an empty group of drawing elements.
587 *
588 * @param {goog.graphics.GroupElement=} opt_group The group wrapper
589 * element to append to. If not specified, appends to the main canvas.
590 *
591 * @return {!goog.graphics.CanvasGroupElement} The newly created group.
592 * @override
593 */
594 goog.graphics.CanvasGraphics.prototype.createGroup = function(opt_group) {
595 var group = new goog.graphics.CanvasGroupElement(this);
596
597 opt_group = opt_group || this.canvasElement;
598
599 // TODO(robbyw): Moving up to any parent group should not force redraw.
600 if (opt_group == this.canvasElement || opt_group == this.lastGroup_) {
601 this.lastGroup_ = group;
602 }
603
604 this.append(group, opt_group);
605
606 return group;
607 };
608
609
610 /**
611 * Measure and return the width (in pixels) of a given text string.
612 * Text measurement is needed to make sure a text can fit in the allocated
613 * area. The way text length is measured is by writing it into a div that is
614 * after the visible area, measure the div width, and immediately erase the
615 * written value.
616 *
617 * @param {string} text The text string to measure.
618 * @param {goog.graphics.Font} font The font object describing the font style.
619 * @override
620 */
621 goog.graphics.CanvasGraphics.prototype.getTextWidth = goog.abstractMethod;
622
623
624 /**
625 * Disposes of the component by removing event handlers, detacing DOM nodes from
626 * the document body, and removing references to them.
627 * @override
628 * @protected
629 */
630 goog.graphics.CanvasGraphics.prototype.disposeInternal = function() {
631 this.context_ = null;
632 goog.graphics.CanvasGraphics.superClass_.disposeInternal.call(this);
633 };
634
635
636 /** @override */
637 goog.graphics.CanvasGraphics.prototype.enterDocument = function() {
638 var oldPixelSize = this.getPixelSize();
639 goog.graphics.CanvasGraphics.superClass_.enterDocument.call(this);
640 if (!oldPixelSize) {
641 this.updateSize();
642 this.dispatchEvent(goog.events.EventType.RESIZE);
643 }
644 this.redraw();
645 };
646
647
648 /**
649 * Start preventing redraws - useful for chaining large numbers of changes
650 * together. Not guaranteed to do anything - i.e. only use this for
651 * optimization of a single code path.
652 * @override
653 */
654 goog.graphics.CanvasGraphics.prototype.suspend = function() {
655 this.preventRedraw_ = true;
656 };
657
658
659 /**
660 * Stop preventing redraws. If any redraws had been prevented, a redraw will
661 * be done now.
662 * @override
663 */
664 goog.graphics.CanvasGraphics.prototype.resume = function() {
665 this.preventRedraw_ = false;
666
667 if (this.needsRedraw_) {
668 this.redraw();
669 this.needsRedraw_ = false;
670 }
671 };
672
673
674 /**
675 * Removes an element from the Canvas.
676 * @param {goog.graphics.Element} elem the element to remove.
677 * @override
678 */
679 goog.graphics.CanvasGraphics.prototype.removeElement = function(elem) {
680 if (!elem) {
681 return;
682 }
683 this.canvasElement.removeElement(elem);
684 this.redraw();
685 };