2 YUI 3.13.0 (build 508226d)
3 Copyright 2013 Yahoo! Inc. All rights reserved.
4 Licensed under the BSD License.
5 http://yuilibrary.com/license/
8 YUI.add('graphics-canvas', function (Y, NAME) {
10 var IMPLEMENTATION = "canvas",
12 SPLITPATHPATTERN = /[a-z][^a-z]*/ig,
13 SPLITARGSPATTERN = /[\-]?[0-9]*[0-9|\.][0-9]*/g,
14 DOCUMENT = Y.config.doc,
16 AttributeLite = Y.AttributeLite,
26 PARSE_FLOAT = parseFloat,
27 IS_NUMBER = Y_LANG.isNumber,
29 TORGB = Y_Color.toRGB,
30 TOHEX = Y_Color.toHex,
31 _getClassName = Y.ClassNameManager.getClassName;
34 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> implementation of the <a href="Drawing.html">`Drawing`</a> class.
35 * `CanvasDrawing` is not intended to be used directly. Instead, use the <a href="Drawing.html">`Drawing`</a> class.
36 * If the browser lacks <a href="http://www.w3.org/TR/SVG/">SVG</a> capabilities but has
37 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> capabilities, the <a href="Drawing.html">`Drawing`</a>
38 * class will point to the `CanvasDrawing` class.
41 * @class CanvasDrawing
44 function CanvasDrawing()
48 CanvasDrawing.prototype = {
50 * Maps path to methods
52 * @property _pathSymbolToMethod
56 _pathSymbolToMethod: {
63 Q: "quadraticCurveTo",
64 q: "relativeQuadraticCurveTo",
70 * Current x position of the drawing.
79 * Current y position of the drqwing.
88 * Parses hex color string and alpha value to rgba
91 * @param {Object} val Color value to parse. Can be hex string, rgb or name.
92 * @param {Number} alpha Numeric value between 0 and 1 representing the alpha level.
95 _toRGBA: function(val, alpha) {
96 alpha = (alpha !== undefined) ? alpha : 1;
97 if (!Y_Color.re_RGB.test(val)) {
101 if(Y_Color.re_hex.exec(val)) {
103 PARSE_INT(RE.$1, 16),
104 PARSE_INT(RE.$2, 16),
106 ].join(',') + ',' + alpha + ')';
112 * Converts color to rgb format
115 * @param val Color value to convert.
118 _toRGB: function(val) {
123 * Sets the size of the graphics object.
126 * @param w {Number} width to set for the instance.
127 * @param h {Number} height to set for the instance.
130 setSize: function(w, h) {
131 if(this.get("autoSize"))
133 if(w > this.node.getAttribute("width"))
135 this.node.style.width = w + "px";
136 this.node.setAttribute("width", w);
138 if(h > this.node.getAttribute("height"))
140 this.node.style.height = h + "px";
141 this.node.setAttribute("height", h);
147 * Tracks coordinates. Used to calculate the start point of dashed lines.
149 * @method _updateCoords
150 * @param {Number} x x-coordinate
151 * @param {Number} y y-coordinate
154 _updateCoords: function(x, y)
156 this._xcoords.push(x);
157 this._ycoords.push(y);
163 * Clears the coordinate arrays. Called at the end of a drawing operation.
165 * @method _clearAndUpdateCoords
168 _clearAndUpdateCoords: function()
170 var x = this._xcoords.pop() || 0,
171 y = this._ycoords.pop() || 0;
172 this._updateCoords(x, y);
176 * Moves the shape's dom node.
178 * @method _updateNodePosition
181 _updateNodePosition: function()
183 var node = this.get("node"),
186 node.style.position = "absolute";
187 node.style.left = (x + this._left) + "px";
188 node.style.top = (y + this._top) + "px";
192 * Queues up a method to be executed when a shape redraws.
194 * @method _updateDrawingQueue
195 * @param {Array} val An array containing data that can be parsed into a method and arguments. The value at zero-index
196 * of the array is a string reference of the drawing method that will be called. All subsequent indices are argument for
197 * that method. For example, `lineTo(10, 100)` would be structured as:
198 * `["lineTo", 10, 100]`.
201 _updateDrawingQueue: function(val)
203 this._methods.push(val);
207 * Draws a line segment from the current drawing position to the specified x and y coordinates.
210 * @param {Number} point1 x-coordinate for the end point.
211 * @param {Number} point2 y-coordinate for the end point.
216 this._lineTo.apply(this, [Y.Array(arguments), false]);
221 * Draws a line segment from the current drawing position to the relative x and y coordinates.
224 * @param {Number} point1 x-coordinate for the end point.
225 * @param {Number} point2 y-coordinate for the end point.
228 relativeLineTo: function()
230 this._lineTo.apply(this, [Y.Array(arguments), true]);
235 * Implements lineTo methods.
238 * @param {Array} args The arguments to be used.
239 * @param {Boolean} relative Indicates whether or not to use relative coordinates.
242 _lineTo: function(args, relative)
244 var point1 = args[0],
249 wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0,
250 relativeX = relative ? parseFloat(this._currentX) : 0,
251 relativeY = relative ? parseFloat(this._currentY) : 0;
252 if(!this._lineToMethods)
254 this._lineToMethods = [];
256 len = args.length - 1;
257 if (typeof point1 === 'string' || typeof point1 === 'number') {
258 for (i = 0; i < len; i = i + 2) {
259 x = parseFloat(args[i]);
260 y = parseFloat(args[i + 1]);
263 this._updateDrawingQueue(["lineTo", x, y]);
264 this._trackSize(x - wt, y - wt);
265 this._trackSize(x + wt, y + wt);
266 this._updateCoords(x, y);
271 for (i = 0; i < len; i = i + 1)
273 x = parseFloat(args[i][0]);
274 y = parseFloat(args[i][1]);
275 this._updateDrawingQueue(["lineTo", x, y]);
276 this._lineToMethods[this._lineToMethods.length] = this._methods[this._methods.length - 1];
277 this._trackSize(x - wt, y - wt);
278 this._trackSize(x + wt, y + wt);
279 this._updateCoords(x, y);
282 this._drawingComplete = false;
287 * Moves the current drawing position to specified x and y coordinates.
290 * @param {Number} x x-coordinate for the end point.
291 * @param {Number} y y-coordinate for the end point.
296 this._moveTo.apply(this, [Y.Array(arguments), false]);
301 * Moves the current drawing position relative to specified x and y coordinates.
303 * @method relativeMoveTo
304 * @param {Number} x x-coordinate for the end point.
305 * @param {Number} y y-coordinate for the end point.
308 relativeMoveTo: function()
310 this._moveTo.apply(this, [Y.Array(arguments), true]);
315 * Implements moveTo methods.
318 * @param {Array} args The arguments to be used.
319 * @param {Boolean} relative Indicates whether or not to use relative coordinates.
322 _moveTo: function(args, relative) {
323 var wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0,
324 relativeX = relative ? parseFloat(this._currentX) : 0,
325 relativeY = relative ? parseFloat(this._currentY) : 0,
326 x = parseFloat(args[0]) + relativeX,
327 y = parseFloat(args[1]) + relativeY;
328 this._updateDrawingQueue(["moveTo", x, y]);
329 this._trackSize(x - wt, y - wt);
330 this._trackSize(x + wt, y + wt);
331 this._updateCoords(x, y);
332 this._drawingComplete = false;
337 * Draws a bezier curve.
340 * @param {Number} cp1x x-coordinate for the first control point.
341 * @param {Number} cp1y y-coordinate for the first control point.
342 * @param {Number} cp2x x-coordinate for the second control point.
343 * @param {Number} cp2y y-coordinate for the second control point.
344 * @param {Number} x x-coordinate for the end point.
345 * @param {Number} y y-coordinate for the end point.
348 curveTo: function() {
349 this._curveTo.apply(this, [Y.Array(arguments), false]);
354 * Draws a bezier curve relative to the current coordinates.
357 * @param {Number} cp1x x-coordinate for the first control point.
358 * @param {Number} cp1y y-coordinate for the first control point.
359 * @param {Number} cp2x x-coordinate for the second control point.
360 * @param {Number} cp2y y-coordinate for the second control point.
361 * @param {Number} x x-coordinate for the end point.
362 * @param {Number} y y-coordinate for the end point.
365 relativeCurveTo: function() {
366 this._curveTo.apply(this, [Y.Array(arguments), true]);
371 * Implements curveTo methods.
374 * @param {Array} args The arguments to be used.
375 * @param {Boolean} relative Indicates whether or not to use relative coordinates.
378 _curveTo: function(args, relative) {
394 relativeX = relative ? parseFloat(this._currentX) : 0,
395 relativeY = relative ? parseFloat(this._currentY) : 0;
396 len = args.length - 5;
397 for(i = 0; i < len; i = i + 6)
399 cp1x = parseFloat(args[i]) + relativeX;
400 cp1y = parseFloat(args[i + 1]) + relativeY;
401 cp2x = parseFloat(args[i + 2]) + relativeX;
402 cp2y = parseFloat(args[i + 3]) + relativeY;
403 x = parseFloat(args[i + 4]) + relativeX;
404 y = parseFloat(args[i + 5]) + relativeY;
405 this._updateDrawingQueue(["bezierCurveTo", cp1x, cp1y, cp2x, cp2y, x, y]);
406 this._drawingComplete = false;
407 right = Math.max(x, Math.max(cp1x, cp2x));
408 bottom = Math.max(y, Math.max(cp1y, cp2y));
409 left = Math.min(x, Math.min(cp1x, cp2x));
410 top = Math.min(y, Math.min(cp1y, cp2y));
411 w = Math.abs(right - left);
412 h = Math.abs(bottom - top);
413 pts = [[this._currentX, this._currentY] , [cp1x, cp1y], [cp2x, cp2y], [x, y]];
414 this._setCurveBoundingBox(pts, w, h);
421 * Draws a quadratic bezier curve.
423 * @method quadraticCurveTo
424 * @param {Number} cpx x-coordinate for the control point.
425 * @param {Number} cpy y-coordinate for the control point.
426 * @param {Number} x x-coordinate for the end point.
427 * @param {Number} y y-coordinate for the end point.
430 quadraticCurveTo: function() {
431 this._quadraticCurveTo.apply(this, [Y.Array(arguments), false]);
436 * Draws a quadratic bezier curve relative to the current position.
438 * @method relativeQuadraticCurveTo
439 * @param {Number} cpx x-coordinate for the control point.
440 * @param {Number} cpy y-coordinate for the control point.
441 * @param {Number} x x-coordinate for the end point.
442 * @param {Number} y y-coordinate for the end point.
445 relativeQuadraticCurveTo: function() {
446 this._quadraticCurveTo.apply(this, [Y.Array(arguments), true]);
451 * Implements quadraticCurveTo methods.
453 * @method _quadraticCurveTo
454 * @param {Array} args The arguments to be used.
455 * @param {Boolean} relative Indicates whether or not to use relative coordinates.
458 _quadraticCurveTo: function(args, relative) {
471 len = args.length - 3,
472 relativeX = relative ? parseFloat(this._currentX) : 0,
473 relativeY = relative ? parseFloat(this._currentY) : 0;
474 for(i = 0; i < len; i = i + 4)
476 cpx = parseFloat(args[i]) + relativeX;
477 cpy = parseFloat(args[i + 1]) + relativeY;
478 x = parseFloat(args[i + 2]) + relativeX;
479 y = parseFloat(args[i + 3]) + relativeY;
480 this._drawingComplete = false;
481 right = Math.max(x, cpx);
482 bottom = Math.max(y, cpy);
483 left = Math.min(x, cpx);
484 top = Math.min(y, cpy);
485 w = Math.abs(right - left);
486 h = Math.abs(bottom - top);
487 pts = [[this._currentX, this._currentY] , [cpx, cpy], [x, y]];
488 this._setCurveBoundingBox(pts, w, h);
489 this._updateDrawingQueue(["quadraticCurveTo", cpx, cpy, x, y]);
490 this._updateCoords(x, y);
496 * Draws a circle. Used internally by `CanvasCircle` class.
499 * @param {Number} x y-coordinate
500 * @param {Number} y x-coordinate
501 * @param {Number} r radius
505 drawCircle: function(x, y, radius) {
507 endAngle = 2 * Math.PI,
508 wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0,
511 this._drawingComplete = false;
512 this._trackSize(x + circum, y + circum);
513 this._trackSize(x - wt, y - wt);
514 this._updateCoords(x, y);
515 this._updateDrawingQueue(["arc", x + radius, y + radius, radius, startAngle, endAngle, false]);
522 * @method drawDiamond
523 * @param {Number} x y-coordinate
524 * @param {Number} y x-coordinate
525 * @param {Number} width width
526 * @param {Number} height height
530 drawDiamond: function(x, y, width, height)
532 var midWidth = width * 0.5,
533 midHeight = height * 0.5;
534 this.moveTo(x + midWidth, y);
535 this.lineTo(x + width, y + midHeight);
536 this.lineTo(x + midWidth, y + height);
537 this.lineTo(x, y + midHeight);
538 this.lineTo(x + midWidth, y);
543 * Draws an ellipse. Used internally by `CanvasEllipse` class.
545 * @method drawEllipse
546 * @param {Number} x x-coordinate
547 * @param {Number} y y-coordinate
548 * @param {Number} w width
549 * @param {Number} h height
553 drawEllipse: function(x, y, w, h) {
555 theta = -(45/180) * Math.PI,
561 centerX = x + radius,
562 centerY = y + yRadius,
563 ax, ay, bx, by, cx, cy,
564 wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0;
566 ax = centerX + Math.cos(0) * radius;
567 ay = centerY + Math.sin(0) * yRadius;
569 for(i = 0; i < l; i++)
572 angleMid = angle - (theta / 2);
573 bx = centerX + Math.cos(angle) * radius;
574 by = centerY + Math.sin(angle) * yRadius;
575 cx = centerX + Math.cos(angleMid) * (radius / Math.cos(theta / 2));
576 cy = centerY + Math.sin(angleMid) * (yRadius / Math.cos(theta / 2));
577 this._updateDrawingQueue(["quadraticCurveTo", cx, cy, bx, by]);
579 this._trackSize(x + w + wt, y + h + wt);
580 this._trackSize(x - wt, y - wt);
581 this._updateCoords(x, y);
589 * @param {Number} x x-coordinate
590 * @param {Number} y y-coordinate
591 * @param {Number} w width
592 * @param {Number} h height
595 drawRect: function(x, y, w, h) {
596 this._drawingComplete = false;
598 this.lineTo(x + w, y);
599 this.lineTo(x + w, y + h);
600 this.lineTo(x, y + h);
606 * Draws a rectangle with rounded corners.
609 * @param {Number} x x-coordinate
610 * @param {Number} y y-coordinate
611 * @param {Number} w width
612 * @param {Number} h height
613 * @param {Number} ew width of the ellipse used to draw the rounded corners
614 * @param {Number} eh height of the ellipse used to draw the rounded corners
617 drawRoundRect: function(x, y, w, h, ew, eh) {
618 this._drawingComplete = false;
619 this.moveTo( x, y + eh);
620 this.lineTo(x, y + h - eh);
621 this.quadraticCurveTo(x, y + h, x + ew, y + h);
622 this.lineTo(x + w - ew, y + h);
623 this.quadraticCurveTo(x + w, y + h, x + w, y + h - eh);
624 this.lineTo(x + w, y + eh);
625 this.quadraticCurveTo(x + w, y, x + w - ew, y);
626 this.lineTo(x + ew, y);
627 this.quadraticCurveTo(x, y, x, y + eh);
635 * @param {Number} x x-coordinate of the wedge's center point
636 * @param {Number} y y-coordinate of the wedge's center point
637 * @param {Number} startAngle starting angle in degrees
638 * @param {Number} arc sweep of the wedge. Negative values draw clockwise.
639 * @param {Number} radius radius of wedge. If [optional] yRadius is defined, then radius is the x radius.
640 * @param {Number} yRadius [optional] y radius for wedge.
644 drawWedge: function(x, y, startAngle, arc, radius, yRadius)
646 var wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0,
659 yRadius = yRadius || radius;
661 this._drawingComplete = false;
662 // move to x,y position
663 this._updateDrawingQueue(["moveTo", x, y]);
665 yRadius = yRadius || radius;
667 // limit sweep to reasonable numbers
668 if(Math.abs(arc) > 360)
673 // First we calculate how many segments are needed
675 segs = Math.ceil(Math.abs(arc) / 45);
677 // Now calculate the sweep of each segment.
678 segAngle = arc / segs;
680 // The math requires radians rather than degrees. To convert from degrees
681 // use the formula (degrees/180)*Math.PI to get radians.
682 theta = -(segAngle / 180) * Math.PI;
684 // convert angle startAngle to radians
685 angle = (startAngle / 180) * Math.PI;
687 // draw the curve in segments no larger than 45 degrees.
690 // draw a line from the center to the start of the curve
691 ax = x + Math.cos(startAngle / 180 * Math.PI) * radius;
692 ay = y + Math.sin(startAngle / 180 * Math.PI) * yRadius;
694 // Loop for drawing curve segments
695 for(i = 0; i < segs; ++i)
698 angleMid = angle - (theta / 2);
699 bx = x + Math.cos(angle) * radius;
700 by = y + Math.sin(angle) * yRadius;
701 cx = x + Math.cos(angleMid) * (radius / Math.cos(theta / 2));
702 cy = y + Math.sin(angleMid) * (yRadius / Math.cos(theta / 2));
703 this._updateDrawingQueue(["quadraticCurveTo", cx, cy, bx, by]);
705 // close the wedge by drawing a line to the center
706 this._updateDrawingQueue(["lineTo", x, y]);
708 this._trackSize(-wt , -wt);
709 this._trackSize((radius * 2) + wt, (radius * 2) + wt);
714 * Completes a drawing operation.
725 * Ends a fill and stroke
730 closePath: function()
732 this._updateDrawingQueue(["closePath"]);
733 this._updateDrawingQueue(["beginPath"]);
738 * Clears the graphics object.
747 this._context.clearRect(0, 0, this.node.width, this.node.height);
754 * Returns a linear gradient fill
756 * @method _getLinearGradient
757 * @return CanvasGradient
760 _getLinearGradient: function() {
761 var isNumber = Y.Lang.isNumber,
762 fill = this.get("fill"),
772 w = this.get("width"),
773 h = this.get("height"),
774 r = fill.rotation || 0,
779 radCon = Math.PI/180,
780 tanRadians = parseFloat(parseFloat(Math.tan(r * radCon)).toFixed(8));
781 if(Math.abs(tanRadians) * w/2 >= h/2)
793 x1 = cx - ((cy - y1)/tanRadians);
794 x2 = cx - ((cy - y2)/tanRadians);
798 if(r > 90 && r < 270)
808 y1 = ((tanRadians * (cx - x1)) - cy) * -1;
809 y2 = ((tanRadians * (cx - x2)) - cy) * -1;
811 gradient = this._context.createLinearGradient(x1, y1, x2, y2);
812 for(i = 0; i < len; ++i)
815 opacity = stop.opacity;
817 offset = stop.offset;
818 if(isNumber(opacity))
820 opacity = Math.max(0, Math.min(1, opacity));
821 color = this._toRGBA(color, opacity);
825 color = TORGB(color);
827 offset = stop.offset || i/(len - 1);
828 gradient.addColorStop(offset, color);
834 * Returns a radial gradient fill
836 * @method _getRadialGradient
837 * @return CanvasGradient
840 _getRadialGradient: function() {
841 var isNumber = Y.Lang.isNumber,
842 fill = this.get("fill"),
855 w = this.get("width"),
856 h = this.get("height"),
869 d = Math.sqrt( Math.pow(Math.abs(xc - x1), 2) + Math.pow(Math.abs(yc - y1), 2) );
873 //hack. gradient won't show if it is exactly on the edge of the arc
878 xn = (x1 - xc)/ratio;
879 yn = (y1 - yc)/ratio;
880 xn = xn > 0 ? Math.floor(xn) : Math.ceil(xn);
881 yn = yn > 0 ? Math.floor(yn) : Math.ceil(yn);
886 //If the gradient radius is greater than the circle's, adjusting the radius stretches the gradient properly.
887 //If the gradient radius is less than the circle's, adjusting the radius of the gradient will not work.
888 //Instead, adjust the color stops to reflect the smaller radius.
891 gradient = this._context.createRadialGradient(x1, y1, r, x2, y2, r * w);
896 gradient = this._context.createRadialGradient(x1, y1, r, x2, y2, w/2);
897 stopMultiplier = r * 2;
899 for(i = 0; i < len; ++i)
902 opacity = stop.opacity;
904 offset = stop.offset;
905 if(isNumber(opacity))
907 opacity = Math.max(0, Math.min(1, opacity));
908 color = this._toRGBA(color, opacity);
912 color = TORGB(color);
914 offset = stop.offset || i/(len - 1);
915 offset *= stopMultiplier;
918 gradient.addColorStop(offset, color);
931 _initProps: function() {
933 this._lineToMethods = [];
947 * Indicates a drawing has completed.
949 * @property _drawingComplete
953 _drawingComplete: false,
956 * Creates canvas element
958 * @method _createGraphic
959 * @return HTMLCanvasElement
962 _createGraphic: function() {
963 var graphic = Y.config.doc.createElement('canvas');
968 * Returns the points on a curve
970 * @method getBezierData
971 * @param Array points Array containing the begin, end and control points of a curve.
972 * @param Number t The value for incrementing the next set of points.
976 getBezierData: function(points, t) {
977 var n = points.length,
982 for (i = 0; i < n; ++i){
983 tmp[i] = [points[i][0], points[i][1]]; // save input
986 for (j = 1; j < n; ++j) {
987 for (i = 0; i < n - j; ++i) {
988 tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0];
989 tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1];
992 return [ tmp[0][0], tmp[0][1] ];
996 * Calculates the bounding box for a curve
998 * @method _setCurveBoundingBox
999 * @param Array pts Array containing points for start, end and control points of a curve.
1000 * @param Number w Width used to calculate the number of points to describe the curve.
1001 * @param Number h Height used to calculate the number of points to describe the curve.
1004 _setCurveBoundingBox: function(pts, w, h)
1007 left = this._currentX,
1009 top = this._currentY,
1011 len = Math.round(Math.sqrt((w * w) + (h * h))),
1013 wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0,
1015 for(i = 0; i < len; ++i)
1017 xy = this.getBezierData(pts, t * i);
1018 left = isNaN(left) ? xy[0] : Math.min(xy[0], left);
1019 right = isNaN(right) ? xy[0] : Math.max(xy[0], right);
1020 top = isNaN(top) ? xy[1] : Math.min(xy[1], top);
1021 bottom = isNaN(bottom) ? xy[1] : Math.max(xy[1], bottom);
1023 left = Math.round(left * 10)/10;
1024 right = Math.round(right * 10)/10;
1025 top = Math.round(top * 10)/10;
1026 bottom = Math.round(bottom * 10)/10;
1027 this._trackSize(right + wt, bottom + wt);
1028 this._trackSize(left - wt, top - wt);
1032 * Updates the size of the graphics object
1034 * @method _trackSize
1035 * @param {Number} w width
1036 * @param {Number} h height
1039 _trackSize: function(w, h) {
1040 if (w > this._right) {
1051 if (h > this._bottom)
1055 this._width = this._right - this._left;
1056 this._height = this._bottom - this._top;
1059 Y.CanvasDrawing = CanvasDrawing;
1061 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> implementation of the <a href="Shape.html">`Shape`</a> class.
1062 * `CanvasShape` is not intended to be used directly. Instead, use the <a href="Shape.html">`Shape`</a> class.
1063 * If the browser lacks <a href="http://www.w3.org/TR/SVG/">SVG</a> capabilities but has
1064 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> capabilities, the <a href="Shape.html">`Shape`</a>
1065 * class will point to the `CanvasShape` class.
1068 * @class CanvasShape
1071 CanvasShape = function()
1073 this._transforms = [];
1074 this.matrix = new Y.Matrix();
1075 CanvasShape.superclass.constructor.apply(this, arguments);
1078 CanvasShape.NAME = "shape";
1080 Y.extend(CanvasShape, Y.GraphicBase, Y.mix({
1082 * Init method, invoked during construction.
1083 * Calls `initializer` method.
1090 this.initializer.apply(this, arguments);
1094 * Initializes the shape
1097 * @method _initialize
1099 initializer: function(cfg)
1102 graphic = cfg.graphic,
1103 data = this.get("data");
1106 host._xcoords = [0];
1107 host._ycoords = [0];
1110 this._setGraphic(graphic);
1114 host._parsePathData(data);
1116 host._updateHandler();
1120 * Set the Graphic instance for the shape.
1122 * @method _setGraphic
1123 * @param {Graphic | Node | HTMLElement | String} render This param is used to determine the graphic instance. If it is a
1124 * `Graphic` instance, it will be assigned to the `graphic` attribute. Otherwise, a new Graphic instance will be created
1125 * and rendered into the dom element that the render represents.
1128 _setGraphic: function(render)
1131 if(render instanceof Y.CanvasGraphic)
1133 this._graphic = render;
1137 graphic = new Y.CanvasGraphic({
1140 graphic._appendShape(this);
1141 this._graphic = graphic;
1146 * Add a class name to each node.
1149 * @param {String} className the class name to add to the node's class attribute
1151 addClass: function(className)
1153 var node = this.get("node");
1154 Y.DOM.addClass(node, className);
1158 * Removes a class name from each node.
1160 * @method removeClass
1161 * @param {String} className the class name to remove from the node's class attribute
1163 removeClass: function(className)
1165 var node = this.get("node");
1166 Y.DOM.removeClass(node, className);
1170 * Gets the current position of the node in page coordinates.
1173 * @return Array The XY position of the shape.
1177 var graphic = this.get("graphic"),
1178 parentXY = graphic.getXY(),
1181 return [parentXY[0] + x, parentXY[1] + y];
1185 * Set the position of the shape in page coordinates, regardless of how the node is positioned.
1188 * @param {Array} Contains X & Y values for new position (coordinates are page-based)
1192 var graphic = this.get("graphic"),
1193 parentXY = graphic.getXY(),
1194 x = xy[0] - parentXY[0],
1195 y = xy[1] - parentXY[1];
1198 this._updateNodePosition(x, y);
1202 * Determines whether the node is an ancestor of another HTML element in the DOM hierarchy.
1205 * @param {CanvasShape | HTMLElement} needle The possible node or descendent
1206 * @return Boolean Whether or not this shape is the needle or its ancestor.
1208 contains: function(needle)
1210 var node = needle instanceof Y.Node ? needle._node : needle;
1211 return node === this.node;
1215 * Test if the supplied node matches the supplied selector.
1218 * @param {String} selector The CSS selector to test against.
1219 * @return Boolean Wheter or not the shape matches the selector.
1221 test: function(selector)
1223 return Y.Selector.test(this.node, selector);
1227 * Compares nodes to determine if they match.
1228 * Node instances can be compared to each other and/or HTMLElements.
1230 * @param {HTMLElement | Node} refNode The reference node to compare to the node.
1231 * @return {Boolean} True if the nodes match, false if they do not.
1233 compareTo: function(refNode) {
1234 var node = this.node;
1235 return node === refNode;
1239 * Value function for fill attribute
1241 * @method _getDefaultFill
1245 _getDefaultFill: function() {
1258 * Value function for stroke attribute
1260 * @method _getDefaultStroke
1264 _getDefaultStroke: function()
1275 * Left edge of the path
1284 * Right edge of the path
1293 * Top edge of the path
1302 * Bottom edge of the path
1311 * Creates the dom node for the shape.
1313 * @method createNode
1314 * @return HTMLElement
1317 createNode: function()
1320 node = Y.config.doc.createElement('canvas'),
1321 id = host.get("id"),
1322 concat = host._camelCaseConcat,
1324 host._context = node.getContext('2d');
1325 node.setAttribute("overflow", "visible");
1326 node.style.overflow = "visible";
1327 if(!host.get("visible"))
1329 node.style.visibility = "hidden";
1331 node.setAttribute("id", id);
1335 _getClassName(SHAPE) +
1337 _getClassName(concat(IMPLEMENTATION, SHAPE)) +
1339 _getClassName(name) +
1341 _getClassName(concat(IMPLEMENTATION, name))
1346 * Overrides default `on` method. Checks to see if its a dom interaction event. If so,
1347 * return an event attached to the `node` element. If not, return the normal functionality.
1350 * @param {String} type event type
1351 * @param {Object} callback function
1354 on: function(type, fn)
1356 if(Y.Node.DOM_EVENTS[type])
1358 return Y.on(type, fn, "#" + this.get("id"));
1360 return Y.on.apply(this, arguments);
1364 * Adds a stroke to the shape node.
1366 * @method _strokeChangeHandler
1367 * @param {Object} stroke Properties of the `stroke` attribute.
1370 _setStrokeProps: function(stroke)
1380 color = stroke.color;
1381 weight = PARSE_FLOAT(stroke.weight);
1382 opacity = PARSE_FLOAT(stroke.opacity);
1383 linejoin = stroke.linejoin || "round";
1384 linecap = stroke.linecap || "butt";
1385 dashstyle = stroke.dashstyle;
1386 this._miterlimit = null;
1387 this._dashstyle = (dashstyle && Y.Lang.isArray(dashstyle) && dashstyle.length > 1) ? dashstyle : null;
1388 this._strokeWeight = weight;
1390 if (IS_NUMBER(weight) && weight > 0)
1398 if (IS_NUMBER(opacity)) {
1399 this._strokeStyle = this._toRGBA(color, opacity);
1403 this._strokeStyle = color;
1405 this._linecap = linecap;
1406 if(linejoin === "round" || linejoin === "bevel")
1408 this._linejoin = linejoin;
1412 linejoin = parseInt(linejoin, 10);
1413 if(IS_NUMBER(linejoin))
1415 this._miterlimit = Math.max(linejoin, 1);
1416 this._linejoin = "miter";
1427 * Sets the value of an attribute.
1430 * @param {String|Object} name The name of the attribute. Alternatively, an object of key value pairs can
1431 * be passed in to set multiple attributes at once.
1432 * @param {Any} value The value to set the attribute to. This value is ignored if an object is received as
1438 AttributeLite.prototype.set.apply(host, arguments);
1439 if(host.initialized)
1441 host._updateHandler();
1446 * Adds a fill to the shape node.
1448 * @method _setFillProps
1449 * @param {Object} fill Properties of the `fill` attribute.
1452 _setFillProps: function(fill)
1454 var isNumber = IS_NUMBER,
1462 if(type === "linear" || type === "radial")
1464 this._fillType = type;
1468 opacity = fill.opacity;
1469 if (isNumber(opacity))
1471 opacity = Math.max(0, Math.min(1, opacity));
1472 color = this._toRGBA(color, opacity);
1476 color = TORGB(color);
1479 this._fillColor = color;
1480 this._fillType = 'solid';
1484 this._fillColor = null;
1489 this._fillType = null;
1490 this._fillColor = null;
1495 * Specifies a 2d translation.
1498 * @param {Number} x The value to transate on the x-axis.
1499 * @param {Number} y The value to translate on the y-axis.
1501 translate: function(x, y)
1503 this._translateX += x;
1504 this._translateY += y;
1505 this._addTransform("translate", arguments);
1509 * Translates the shape along the x-axis. When translating x and y coordinates,
1510 * use the `translate` method.
1512 * @method translateX
1513 * @param {Number} x The value to translate.
1515 translateX: function(x)
1517 this._translateX += x;
1518 this._addTransform("translateX", arguments);
1522 * Performs a translate on the y-coordinate. When translating x and y coordinates,
1523 * use the `translate` method.
1525 * @method translateY
1526 * @param {Number} y The value to translate.
1528 translateY: function(y)
1530 this._translateY += y;
1531 this._addTransform("translateY", arguments);
1535 * Skews the shape around the x-axis and y-axis.
1538 * @param {Number} x The value to skew on the x-axis.
1539 * @param {Number} y The value to skew on the y-axis.
1543 this._addTransform("skew", arguments);
1547 * Skews the shape around the x-axis.
1550 * @param {Number} x x-coordinate
1554 this._addTransform("skewX", arguments);
1558 * Skews the shape around the y-axis.
1561 * @param {Number} y y-coordinate
1565 this._addTransform("skewY", arguments);
1569 * Rotates the shape clockwise around it transformOrigin.
1572 * @param {Number} deg The degree of the rotation.
1576 this._addTransform("rotate", arguments);
1580 * Specifies a 2d scaling operation.
1583 * @param {Number} val
1587 this._addTransform("scale", arguments);
1591 * Storage for the transform attribute.
1593 * @property _transform
1600 * Adds a transform to the shape.
1602 * @method _addTransform
1603 * @param {String} type The transform being applied.
1604 * @param {Array} args The arguments for the transform.
1607 _addTransform: function(type, args)
1609 args = Y.Array(args);
1610 this._transform = Y_LANG.trim(this._transform + " " + type + "(" + args.join(", ") + ")");
1612 this._transforms.push(args);
1613 if(this.initialized)
1615 this._updateTransform();
1620 * Applies all transforms.
1622 * @method _updateTransform
1625 _updateTransform: function()
1627 var node = this.node,
1630 transformOrigin = this.get("transformOrigin"),
1631 matrix = this.matrix,
1633 len = this._transforms.length;
1635 if(this._transforms && this._transforms.length > 0)
1637 for(i = 0; i < len; ++i)
1639 key = this._transforms[i].shift();
1642 matrix[key].apply(matrix, this._transforms[i]);
1645 transform = matrix.toCSSText();
1648 this._graphic.addToRedrawQueue(this);
1649 transformOrigin = (100 * transformOrigin[0]) + "% " + (100 * transformOrigin[1]) + "%";
1650 Y_DOM.setStyle(node, "transformOrigin", transformOrigin);
1653 Y_DOM.setStyle(node, "transform", transform);
1655 this._transforms = [];
1659 * Updates `Shape` based on attribute changes.
1661 * @method _updateHandler
1664 _updateHandler: function()
1667 this._updateTransform();
1671 * Updates the shape.
1678 var node = this.node;
1681 node.style.left = this.get("x") + "px";
1682 node.style.top = this.get("y") + "px";
1686 * Completes a shape or drawing
1688 * @method _closePath
1691 _closePath: function()
1697 var node = this.get("node"),
1698 w = this._right - this._left,
1699 h = this._bottom - this._top,
1700 context = this._context,
1702 cachedMethods = this._methods.concat(),
1709 this._context.clearRect(0, 0, node.width, node.height);
1712 len = cachedMethods.length;
1717 for(i = 0; i < len; ++i)
1719 methods[i] = cachedMethods[i].concat();
1721 argsLen = (args[0] === "quadraticCurveTo" || args[0] === "bezierCurveTo") ? args.length : 3;
1722 for(j = 1; j < argsLen; ++j)
1726 args[j] = args[j] - this._top;
1730 args[j] = args[j] - this._left;
1734 node.setAttribute("width", Math.min(w, 2000));
1735 node.setAttribute("height", Math.min(2000, h));
1736 context.beginPath();
1737 for(i = 0; i < len; ++i)
1739 args = methods[i].concat();
1740 if(args && args.length > 0)
1742 method = args.shift();
1745 if(method === "closePath")
1747 context.closePath();
1748 this._strokeAndFill(context);
1750 else if(method && method === "lineTo" && this._dashstyle)
1752 args.unshift(this._xcoords[i] - this._left, this._ycoords[i] - this._top);
1753 this._drawDashedLine.apply(this, args);
1757 context[method].apply(context, args);
1763 this._strokeAndFill(context);
1764 this._drawingComplete = true;
1765 this._clearAndUpdateCoords();
1766 this._updateNodePosition();
1767 this._methods = cachedMethods;
1772 * Completes a stroke and/or fill operation on the context.
1774 * @method _strokeAndFill
1775 * @param {Context} Reference to the context element of the canvas instance.
1778 _strokeAndFill: function(context)
1782 if(this._fillType === "linear")
1784 context.fillStyle = this._getLinearGradient();
1786 else if(this._fillType === "radial")
1788 context.fillStyle = this._getRadialGradient();
1792 context.fillStyle = this._fillColor;
1794 context.closePath();
1799 if(this._strokeWeight)
1801 context.lineWidth = this._strokeWeight;
1803 context.lineCap = this._linecap;
1804 context.lineJoin = this._linejoin;
1805 if(this._miterlimit)
1807 context.miterLimit = this._miterlimit;
1809 context.strokeStyle = this._strokeStyle;
1815 * Draws a dashed line between two points.
1817 * @method _drawDashedLine
1818 * @param {Number} xStart The x position of the start of the line
1819 * @param {Number} yStart The y position of the start of the line
1820 * @param {Number} xEnd The x position of the end of the line
1821 * @param {Number} yEnd The y position of the end of the line
1824 _drawDashedLine: function(xStart, yStart, xEnd, yEnd)
1826 var context = this._context,
1827 dashsize = this._dashstyle[0],
1828 gapsize = this._dashstyle[1],
1829 segmentLength = dashsize + gapsize,
1830 xDelta = xEnd - xStart,
1831 yDelta = yEnd - yStart,
1832 delta = Math.sqrt(Math.pow(xDelta, 2) + Math.pow(yDelta, 2)),
1833 segmentCount = Math.floor(Math.abs(delta / segmentLength)),
1834 radians = Math.atan2(yDelta, xDelta),
1838 xDelta = Math.cos(radians) * segmentLength;
1839 yDelta = Math.sin(radians) * segmentLength;
1841 for(i = 0; i < segmentCount; ++i)
1843 context.moveTo(xCurrent, yCurrent);
1844 context.lineTo(xCurrent + Math.cos(radians) * dashsize, yCurrent + Math.sin(radians) * dashsize);
1849 context.moveTo(xCurrent, yCurrent);
1850 delta = Math.sqrt((xEnd - xCurrent) * (xEnd - xCurrent) + (yEnd - yCurrent) * (yEnd - yCurrent));
1852 if(delta > dashsize)
1854 context.lineTo(xCurrent + Math.cos(radians) * dashsize, yCurrent + Math.sin(radians) * dashsize);
1858 context.lineTo(xCurrent + Math.cos(radians) * delta, yCurrent + Math.sin(radians) * delta);
1861 context.moveTo(xEnd, yEnd);
1865 * Returns the bounds for a shape.
1867 * Calculates the a new bounding box from the original corner coordinates (base on size and position) and the transform matrix.
1868 * The calculated bounding box is used by the graphic instance to calculate its viewBox.
1873 getBounds: function()
1875 var type = this._type,
1876 w = this.get("width"),
1877 h = this.get("height"),
1884 w = this._right - this._left;
1885 h = this._bottom - this._top;
1887 return this._getContentRect(w, h, x, y);
1891 * Calculates the bounding box for the shape.
1893 * @method _getContentRect
1894 * @param {Number} w width of the shape
1895 * @param {Number} h height of the shape
1896 * @param {Number} x x-coordinate of the shape
1897 * @param {Number} y y-coordinate of the shape
1900 _getContentRect: function(w, h, x, y)
1902 var transformOrigin = this.get("transformOrigin"),
1903 transformX = transformOrigin[0] * w,
1904 transformY = transformOrigin[1] * h,
1905 transforms = this.matrix.getTransformArray(this.get("transform")),
1906 matrix = new Y.Matrix(),
1908 len = transforms.length,
1912 if(this._type === "path")
1914 transformX = transformX + x;
1915 transformY = transformY + y;
1917 transformX = !isNaN(transformX) ? transformX : 0;
1918 transformY = !isNaN(transformY) ? transformY : 0;
1919 matrix.translate(transformX, transformY);
1920 for(i = 0; i < len; i = i + 1)
1922 transform = transforms[i];
1923 key = transform.shift();
1926 matrix[key].apply(matrix, transform);
1929 matrix.translate(-transformX, -transformY);
1930 contentRect = matrix.getContentRect(w, h, x, y);
1935 * Places the shape above all other shapes.
1941 var graphic = this.get("graphic");
1944 graphic._toFront(this);
1949 * Places the shape underneath all other shapes.
1955 var graphic = this.get("graphic");
1958 graphic._toBack(this);
1963 * Parses path data string and call mapped methods.
1965 * @method _parsePathData
1966 * @param {String} val The path data
1969 _parsePathData: function(val)
1974 commandArray = Y.Lang.trim(val.match(SPLITPATHPATTERN)),
1978 symbolToMethod = this._pathSymbolToMethod;
1982 len = commandArray.length || 0;
1983 for(i = 0; i < len; i = i + 1)
1985 str = commandArray[i];
1986 methodSymbol = str.substr(0, 1);
1987 args = str.substr(1).match(SPLITARGSPATTERN);
1988 method = symbolToMethod[methodSymbol];
1993 this[method].apply(this, args);
1997 this[method].apply(this);
2006 * Destroys the shape instance.
2012 var graphic = this.get("graphic");
2015 graphic.removeShape(this);
2024 * Implementation for shape destruction
2029 _destroy: function()
2033 Y.Event.purgeElement(this.node, true);
2034 if(this.node.parentNode)
2036 this.node.style.visibility = "";
2037 this.node.parentNode.removeChild(this.node);
2039 this._context = null;
2043 }, Y.CanvasDrawing.prototype));
2045 CanvasShape.ATTRS = {
2047 * An array of x, y values which indicates the transformOrigin in which to rotate the shape. Valid values range between 0 and 1 representing a
2048 * fraction of the shape's corresponding bounding box dimension. The default value is [0.5, 0.5].
2050 * @config transformOrigin
2061 * <p>A string containing, in order, transform operations applied to the shape instance. The `transform` string can contain the following values:
2064 * <dt>rotate</dt><dd>Rotates the shape clockwise around it transformOrigin.</dd>
2065 * <dt>translate</dt><dd>Specifies a 2d translation.</dd>
2066 * <dt>skew</dt><dd>Skews the shape around the x-axis and y-axis.</dd>
2067 * <dt>scale</dt><dd>Specifies a 2d scaling operation.</dd>
2068 * <dt>translateX</dt><dd>Translates the shape along the x-axis.</dd>
2069 * <dt>translateY</dt><dd>Translates the shape along the y-axis.</dd>
2070 * <dt>skewX</dt><dd>Skews the shape around the x-axis.</dd>
2071 * <dt>skewY</dt><dd>Skews the shape around the y-axis.</dd>
2072 * <dt>matrix</dt><dd>Specifies a 2D transformation matrix comprised of the specified six values.</dd>
2075 * <p>Applying transforms through the transform attribute will reset the transform matrix and apply a new transform. The shape class also contains
2076 * corresponding methods for each transform that will apply the transform to the current matrix. The below code illustrates how you might use the
2077 * `transform` attribute to instantiate a recangle with a rotation of 45 degrees.</p>
2078 var myRect = new Y.Rect({
2082 transform: "rotate(45)"
2084 * <p>The code below would apply `translate` and `rotate` to an existing shape.</p>
2086 myRect.set("transform", "translate(40, 50) rotate(45)");
2091 setter: function(val)
2094 this._transforms = this.matrix.getTransformArray(val);
2095 this._transform = val;
2101 return this._transform;
2106 * Dom node for the shape
2122 * Unique id for class instance.
2133 setter: function(val)
2135 var node = this.node;
2138 node.setAttribute("id", val);
2145 * Indicates the width of the shape
2155 * Indicates the height of the shape
2165 * Indicates the x position of shape.
2175 * Indicates the y position of shape.
2185 * Indicates whether the shape is visible.
2193 setter: function(val){
2194 var node = this.get("node"),
2195 visibility = val ? "visible" : "hidden";
2198 node.style.visibility = visibility;
2205 * Contains information about the fill of the shape.
2207 * <dt>color</dt><dd>The color of the fill.</dd>
2208 * <dt>opacity</dt><dd>Number between 0 and 1 that indicates the opacity of the fill. The default value is 1.</dd>
2209 * <dt>type</dt><dd>Type of fill.
2211 * <dt>solid</dt><dd>Solid single color fill. (default)</dd>
2212 * <dt>linear</dt><dd>Linear gradient fill.</dd>
2213 * <dt>radial</dt><dd>Radial gradient fill.</dd>
2217 * <p>If a `linear` or `radial` is specified as the fill type. The following additional property is used:
2219 * <dt>stops</dt><dd>An array of objects containing the following properties:
2221 * <dt>color</dt><dd>The color of the stop.</dd>
2222 * <dt>opacity</dt><dd>Number between 0 and 1 that indicates the opacity of the stop. The default value is 1.
2223 * Note: No effect for IE 6 - 8</dd>
2224 * <dt>offset</dt><dd>Number between 0 and 1 indicating where the color stop is positioned.</dd>
2227 * <p>Linear gradients also have the following property:</p>
2228 * <dt>rotation</dt><dd>Linear gradients flow left to right by default. The rotation property allows you to change the
2229 * flow by rotation. (e.g. A rotation of 180 would make the gradient pain from right to left.)</dd>
2230 * <p>Radial gradients have the following additional properties:</p>
2231 * <dt>r</dt><dd>Radius of the gradient circle.</dd>
2232 * <dt>fx</dt><dd>Focal point x-coordinate of the gradient.</dd>
2233 * <dt>fy</dt><dd>Focal point y-coordinate of the gradient.</dd>
2235 * <p>The corresponding `SVGShape` class implements the following additional properties.</p>
2238 * <p>The x-coordinate of the center of the gradient circle. Determines where the color stop begins. The default value 0.5.</p>
2239 * <p><strong>Note: </strong>Currently, this property is not implemented for corresponding `CanvasShape` and
2240 * `VMLShape` classes which are used on Android or IE 6 - 8.</p>
2243 * <p>The y-coordinate of the center of the gradient circle. Determines where the color stop begins. The default value 0.5.</p>
2244 * <p><strong>Note: </strong>Currently, this property is not implemented for corresponding `CanvasShape` and `VMLShape`
2245 * classes which are used on Android or IE 6 - 8.</p>
2248 * <p>These properties are not currently implemented in `CanvasShape` or `VMLShape`.</p>
2254 valueFn: "_getDefaultFill",
2256 setter: function(val)
2259 tmpl = this.get("fill") || this._getDefaultFill();
2260 fill = (val) ? Y.merge(tmpl, val) : null;
2261 if(fill && fill.color)
2263 if(fill.color === undefined || fill.color === "none")
2268 this._setFillProps(fill);
2274 * Contains information about the stroke of the shape.
2276 * <dt>color</dt><dd>The color of the stroke.</dd>
2277 * <dt>weight</dt><dd>Number that indicates the width of the stroke.</dd>
2278 * <dt>opacity</dt><dd>Number between 0 and 1 that indicates the opacity of the stroke. The default value is 1.</dd>
2279 * <dt>dashstyle</dt>Indicates whether to draw a dashed stroke. When set to "none", a solid stroke is drawn. When set
2280 * to an array, the first index indicates the length of the dash. The second index indicates the length of gap.
2281 * <dt>linecap</dt><dd>Specifies the linecap for the stroke. The following values can be specified:
2283 * <dt>butt (default)</dt><dd>Specifies a butt linecap.</dd>
2284 * <dt>square</dt><dd>Specifies a sqare linecap.</dd>
2285 * <dt>round</dt><dd>Specifies a round linecap.</dd>
2288 * <dt>linejoin</dt><dd>Specifies a linejoin for the stroke. The following values can be specified:
2290 * <dt>round (default)</dt><dd>Specifies that the linejoin will be round.</dd>
2291 * <dt>bevel</dt><dd>Specifies a bevel for the linejoin.</dd>
2292 * <dt>miter limit</dt><dd>An integer specifying the miter limit of a miter linejoin. If you want to specify a linejoin
2293 * of miter, you simply specify the limit as opposed to having separate miter and miter limit values.</dd>
2302 valueFn: "_getDefaultStroke",
2304 setter: function(val)
2306 var tmpl = this.get("stroke") || this._getDefaultStroke(),
2308 if(val && val.hasOwnProperty("weight"))
2310 wt = parseInt(val.weight, 10);
2316 val = (val) ? Y.merge(tmpl, val) : null;
2317 this._setStrokeProps(val);
2322 //Not used. Remove in future.
2327 // Only implemented in SVG
2328 // Determines whether the instance will receive mouse events.
2330 // @config pointerEvents
2334 value: "visiblePainted"
2338 * Represents an SVG Path string. This will be parsed and added to shape's API to represent the SVG data across all
2339 * implementations. Note that when using VML or SVG implementations, part of this content will be added to the DOM using
2340 * respective VML/SVG attributes. If your content comes from an untrusted source, you will need to ensure that no
2341 * malicious code is included in that content.
2347 setter: function(val)
2349 if(this.get("node"))
2351 this._parsePathData(val);
2358 * Reference to the container Graphic.
2368 return this._graphic;
2372 Y.CanvasShape = CanvasShape;
2374 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> implementation of the <a href="Path.html">`Path`</a> class.
2375 * `CanvasPath` is not intended to be used directly. Instead, use the <a href="Path.html">`Path`</a> class.
2376 * If the browser lacks <a href="http://www.w3.org/TR/SVG/">SVG</a> capabilities but has
2377 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> capabilities, the <a href="Path.html">`Path`</a>
2378 * class will point to the `CanvasPath` class.
2382 * @extends CanvasShape
2384 CanvasPath = function()
2386 CanvasPath.superclass.constructor.apply(this, arguments);
2388 CanvasPath.NAME = "path";
2389 Y.extend(CanvasPath, Y.CanvasShape, {
2391 * Indicates the type of shape
2408 this._updateTransform();
2412 * Creates the dom node for the shape.
2414 * @method createNode
2415 * @return HTMLElement
2418 createNode: function()
2421 node = Y.config.doc.createElement('canvas'),
2423 concat = host._camelCaseConcat,
2424 id = host.get("id");
2425 host._context = node.getContext('2d');
2426 node.setAttribute("overflow", "visible");
2427 node.setAttribute("pointer-events", "none");
2428 node.style.pointerEvents = "none";
2429 node.style.overflow = "visible";
2430 node.setAttribute("id", id);
2434 _getClassName(SHAPE) +
2436 _getClassName(concat(IMPLEMENTATION, SHAPE)) +
2438 _getClassName(name) +
2440 _getClassName(concat(IMPLEMENTATION, name))
2445 * Completes a drawing operation.
2455 CanvasPath.ATTRS = Y.merge(Y.CanvasShape.ATTRS, {
2457 * Indicates the width of the shape
2465 var offset = this._stroke && this._strokeWeight ? (this._strokeWeight * 2) : 0;
2466 return this._width - offset;
2469 setter: function(val)
2477 * Indicates the height of the shape
2485 var offset = this._stroke && this._strokeWeight ? (this._strokeWeight * 2) : 0;
2486 return this._height - offset;
2489 setter: function(val)
2497 * Indicates the path used for the node.
2512 Y.CanvasPath = CanvasPath;
2514 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> implementation of the <a href="Rect.html">`Rect`</a> class.
2515 * `CanvasRect` is not intended to be used directly. Instead, use the <a href="Rect.html">`Rect`</a> class.
2516 * If the browser lacks <a href="http://www.w3.org/TR/SVG/">SVG</a> capabilities but has
2517 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> capabilities, the <a href="Rect.html">`Rect`</a>
2518 * class will point to the `CanvasRect` class.
2524 CanvasRect = function()
2526 CanvasRect.superclass.constructor.apply(this, arguments);
2528 CanvasRect.NAME = "rect";
2529 Y.extend(CanvasRect, Y.CanvasShape, {
2531 * Indicates the type of shape
2547 var w = this.get("width"),
2548 h = this.get("height");
2550 this.drawRect(0, 0, w, h);
2554 CanvasRect.ATTRS = Y.CanvasShape.ATTRS;
2555 Y.CanvasRect = CanvasRect;
2557 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> implementation of the <a href="Ellipse.html">`Ellipse`</a> class.
2558 * `CanvasEllipse` is not intended to be used directly. Instead, use the <a href="Ellipse.html">`Ellipse`</a> class.
2559 * If the browser lacks <a href="http://www.w3.org/TR/SVG/">SVG</a> capabilities but has
2560 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> capabilities, the <a href="Ellipse.html">`Ellipse`</a>
2561 * class will point to the `CanvasEllipse` class.
2564 * @class CanvasEllipse
2567 CanvasEllipse = function()
2569 CanvasEllipse.superclass.constructor.apply(this, arguments);
2572 CanvasEllipse.NAME = "ellipse";
2574 Y.extend(CanvasEllipse, CanvasShape, {
2576 * Indicates the type of shape
2592 var w = this.get("width"),
2593 h = this.get("height");
2595 this.drawEllipse(0, 0, w, h);
2599 CanvasEllipse.ATTRS = Y.merge(CanvasShape.ATTRS, {
2601 * Horizontal radius for the ellipse.
2607 setter: function(val)
2609 this.set("width", val * 2);
2614 var val = this.get("width");
2624 * Vertical radius for the ellipse.
2631 setter: function(val)
2633 this.set("height", val * 2);
2638 var val = this.get("height");
2647 Y.CanvasEllipse = CanvasEllipse;
2649 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> implementation of the <a href="Circle.html">`Circle`</a> class.
2650 * `CanvasCircle` is not intended to be used directly. Instead, use the <a href="Circle.html">`Circle`</a> class.
2651 * If the browser lacks <a href="http://www.w3.org/TR/SVG/">SVG</a> capabilities but has
2652 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> capabilities, the <a href="Circle.html">`Circle`</a>
2653 * class will point to the `CanvasCircle` class.
2656 * @class CanvasCircle
2659 CanvasCircle = function()
2661 CanvasCircle.superclass.constructor.apply(this, arguments);
2664 CanvasCircle.NAME = "circle";
2666 Y.extend(CanvasCircle, Y.CanvasShape, {
2668 * Indicates the type of shape
2684 var radius = this.get("radius");
2688 this.drawCircle(0, 0, radius);
2694 CanvasCircle.ATTRS = Y.merge(Y.CanvasShape.ATTRS, {
2696 * Indicates the width of the shape
2702 setter: function(val)
2704 this.set("radius", val/2);
2710 return this.get("radius") * 2;
2715 * Indicates the height of the shape
2721 setter: function(val)
2723 this.set("radius", val/2);
2729 return this.get("radius") * 2;
2734 * Radius of the circle
2743 Y.CanvasCircle = CanvasCircle;
2748 * @class CanvasPieSlice
2751 CanvasPieSlice = function()
2753 CanvasPieSlice.superclass.constructor.apply(this, arguments);
2755 CanvasPieSlice.NAME = "canvasPieSlice";
2756 Y.extend(CanvasPieSlice, Y.CanvasShape, {
2758 * Indicates the type of shape
2767 * Change event listener
2770 * @method _updateHandler
2774 var x = this.get("cx"),
2776 startAngle = this.get("startAngle"),
2777 arc = this.get("arc"),
2778 radius = this.get("radius");
2781 this._right = radius;
2783 this._bottom = radius;
2784 this.drawWedge(x, y, startAngle, arc, radius);
2788 CanvasPieSlice.ATTRS = Y.mix({
2797 * Starting angle in relation to a circle in which to begin the pie slice drawing.
2799 * @config startAngle
2817 * Radius of the circle in which the pie slice is drawn
2825 }, Y.CanvasShape.ATTRS);
2826 Y.CanvasPieSlice = CanvasPieSlice;
2828 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> implementation of the `Graphic` class.
2829 * `CanvasGraphic` is not intended to be used directly. Instead, use the <a href="Graphic.html">`Graphic`</a> class.
2830 * If the browser lacks <a href="http://www.w3.org/TR/SVG/">SVG</a> capabilities but has
2831 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> capabilities, the <a href="Graphic.html">`Graphic`</a>
2832 * class will point to the `CanvasGraphic` class.
2835 * @class CanvasGraphic
2838 function CanvasGraphic() {
2840 CanvasGraphic.superclass.constructor.apply(this, arguments);
2843 CanvasGraphic.NAME = "canvasGraphic";
2845 CanvasGraphic.ATTRS = {
2847 * Whether or not to render the `Graphic` automatically after to a specified parent node after init. This can be a Node
2848 * instance or a CSS selector string.
2851 * @type Node | String
2856 * Unique id for class instance.
2867 setter: function(val)
2869 var node = this._node;
2872 node.setAttribute("id", val);
2879 * Key value pairs in which a shape instance is associated with its id.
2890 return this._shapes;
2895 * Object containing size and coordinate data for the content of a Graphic in relation to the graphic instance's position.
2897 * @config contentBounds
2906 return this._contentBounds;
2911 * The outermost html element of the Graphic instance.
2927 * Indicates the width of the `Graphic`.
2933 setter: function(val)
2937 this._node.style.width = val + "px";
2944 * Indicates the height of the `Graphic`.
2950 setter: function(val)
2954 this._node.style.height = val + "px";
2961 * Determines the sizing of the Graphic.
2964 * <dt>sizeContentToGraphic</dt><dd>The Graphic's width and height attributes are, either explicitly set through the
2965 * <code>width</code> and <code>height</code> attributes or are determined by the dimensions of the parent element. The
2966 * content contained in the Graphic will be sized to fit with in the Graphic instance's dimensions. When using this
2967 * setting, the <code>preserveAspectRatio</code> attribute will determine how the contents are sized.</dd>
2968 * <dt>sizeGraphicToContent</dt><dd>(Also accepts a value of true) The Graphic's width and height are determined by the
2969 * size and positioning of the content.</dd>
2970 * <dt>false</dt><dd>The Graphic's width and height attributes are, either explicitly set through the <code>width</code>
2971 * and <code>height</code> attributes or are determined by the dimensions of the parent element. The contents of the
2972 * Graphic instance are not affected by this setting.</dd>
2977 * @type Boolean | String
2985 * Determines how content is sized when <code>autoSize</code> is set to <code>sizeContentToGraphic</code>.
2988 * <dt>none<dt><dd>Do not force uniform scaling. Scale the graphic content of the given element non-uniformly if necessary
2989 * such that the element's bounding box exactly matches the viewport rectangle.</dd>
2990 * <dt>xMinYMin</dt><dd>Force uniform scaling position along the top left of the Graphic's node.</dd>
2991 * <dt>xMidYMin</dt><dd>Force uniform scaling horizontally centered and positioned at the top of the Graphic's node.<dd>
2992 * <dt>xMaxYMin</dt><dd>Force uniform scaling positioned horizontally from the right and vertically from the top.</dd>
2993 * <dt>xMinYMid</dt>Force uniform scaling positioned horizontally from the left and vertically centered.</dd>
2994 * <dt>xMidYMid (the default)</dt><dd>Force uniform scaling with the content centered.</dd>
2995 * <dt>xMaxYMid</dt><dd>Force uniform scaling positioned horizontally from the right and vertically centered.</dd>
2996 * <dt>xMinYMax</dt><dd>Force uniform scaling positioned horizontally from the left and vertically from the bottom.</dd>
2997 * <dt>xMidYMax</dt><dd>Force uniform scaling horizontally centered and position vertically from the bottom.</dd>
2998 * <dt>xMaxYMax</dt><dd>Force uniform scaling positioned horizontally from the right and vertically from the bottom.</dd>
3001 * @config preserveAspectRatio
3005 preserveAspectRatio: {
3010 * The contentBounds will resize to greater values but not smaller values. (for performance)
3011 * When resizing the contentBounds down is desirable, set the resizeDown value to true.
3013 * @config resizeDown
3021 * Indicates the x-coordinate for the instance.
3032 setter: function(val)
3037 this._node.style.left = val + "px";
3044 * Indicates the y-coordinate for the instance.
3055 setter: function(val)
3060 this._node.style.top = val + "px";
3067 * Indicates whether or not the instance will automatically redraw after a change is made to a shape.
3068 * This property will get set to false when batching operations.
3080 * Indicates whether the `Graphic` and its children are visible.
3088 setter: function(val)
3090 this._toggleVisible(val);
3096 Y.extend(CanvasGraphic, Y.GraphicBase, {
3098 * Sets the value of an attribute.
3101 * @param {String|Object} name The name of the attribute. Alternatively, an object of key value pairs can
3102 * be passed in to set multiple attributes at once.
3103 * @param {Any} value The value to set the attribute to. This value is ignored if an object is received as
3109 attr = arguments[0],
3113 preserveAspectRatio: true,
3117 forceRedraw = false;
3118 AttributeLite.prototype.set.apply(host, arguments);
3119 if(host._state.autoDraw === true && Y.Object.size(this._shapes) > 0)
3121 if(Y_LANG.isString && redrawAttrs[attr])
3125 else if(Y_LANG.isObject(attr))
3127 for(key in redrawAttrs)
3129 if(redrawAttrs.hasOwnProperty(key) && attr[key])
3144 * Storage for `x` attribute.
3153 * Storage for `y` attribute.
3162 * Gets the current position of the graphic instance in page coordinates.
3165 * @return Array The XY position of the shape.
3169 var node = this._node,
3173 xy = Y.DOM.getXY(node);
3179 * Initializes the class.
3181 * @method initializer
3182 * @param {Object} config Optional attributes
3185 initializer: function() {
3186 var render = this.get("render"),
3187 visibility = this.get("visible") ? "visible" : "hidden",
3188 w = this.get("width") || 0,
3189 h = this.get("height") || 0;
3191 this._redrawQueue = {};
3192 this._contentBounds = {
3198 this._node = DOCUMENT.createElement('div');
3199 this._node.style.position = "absolute";
3200 this._node.style.visibility = visibility;
3201 this.set("width", w);
3202 this.set("height", h);
3205 this.render(render);
3210 * Adds the graphics node to the dom.
3213 * @param {HTMLElement} parentNode node in which to render the graphics node into.
3215 render: function(render) {
3216 var parentNode = render || DOCUMENT.body,
3220 if(render instanceof Y.Node)
3222 parentNode = render._node;
3224 else if(Y.Lang.isString(render))
3226 parentNode = Y.Selector.query(render, DOCUMENT.body, true);
3228 w = this.get("width") || parseInt(Y.DOM.getComputedStyle(parentNode, "width"), 10);
3229 h = this.get("height") || parseInt(Y.DOM.getComputedStyle(parentNode, "height"), 10);
3230 parentNode.appendChild(node);
3231 node.style.display = "block";
3232 node.style.position = "absolute";
3233 node.style.left = "0px";
3234 node.style.top = "0px";
3235 this.set("width", w);
3236 this.set("height", h);
3237 this.parentNode = parentNode;
3242 * Removes all nodes.
3248 this.removeAllShapes();
3251 this._removeChildren(this._node);
3252 if(this._node.parentNode)
3254 this._node.parentNode.removeChild(this._node);
3261 * Generates a shape instance by type.
3264 * @param {Object} cfg attributes for the shape
3267 addShape: function(cfg)
3270 if(!this.get("visible"))
3272 cfg.visible = false;
3274 var ShapeClass = this._getShapeClass(cfg.type),
3275 shape = new ShapeClass(cfg);
3276 this._appendShape(shape);
3281 * Adds a shape instance to the graphic instance.
3283 * @method _appendShape
3284 * @param {Shape} shape The shape instance to be added to the graphic.
3287 _appendShape: function(shape)
3289 var node = shape.node,
3290 parentNode = this._frag || this._node;
3291 if(this.get("autoDraw"))
3293 parentNode.appendChild(node);
3297 this._getDocFrag().appendChild(node);
3302 * Removes a shape instance from from the graphic instance.
3304 * @method removeShape
3305 * @param {Shape|String} shape The instance or id of the shape to be removed.
3307 removeShape: function(shape)
3309 if(!(shape instanceof CanvasShape))
3311 if(Y_LANG.isString(shape))
3313 shape = this._shapes[shape];
3316 if(shape && shape instanceof CanvasShape)
3319 delete this._shapes[shape.get("id")];
3321 if(this.get("autoDraw"))
3329 * Removes all shape instances from the dom.
3331 * @method removeAllShapes
3333 removeAllShapes: function()
3335 var shapes = this._shapes,
3339 if(shapes.hasOwnProperty(i))
3341 shapes[i].destroy();
3348 * Clears the graphics object.
3353 this.removeAllShapes();
3357 * Removes all child nodes.
3359 * @method _removeChildren
3360 * @param {HTMLElement} node
3363 _removeChildren: function(node)
3365 if(node && node.hasChildNodes())
3368 while(node.firstChild)
3370 child = node.firstChild;
3371 this._removeChildren(child);
3372 node.removeChild(child);
3378 * Toggles visibility
3380 * @method _toggleVisible
3381 * @param {Boolean} val indicates visibilitye
3384 _toggleVisible: function(val)
3387 shapes = this._shapes,
3388 visibility = val ? "visible" : "hidden";
3393 if(shapes.hasOwnProperty(i))
3395 shapes[i].set("visible", val);
3401 this._node.style.visibility = visibility;
3406 * Returns a shape class. Used by `addShape`.
3408 * @method _getShapeClass
3409 * @param {Shape | String} val Indicates which shape class.
3413 _getShapeClass: function(val)
3415 var shape = this._shapeClass[val];
3424 * Look up for shape classes. Used by `addShape` to retrieve a class for instantiation.
3426 * @property _shapeClass
3431 circle: Y.CanvasCircle,
3434 ellipse: Y.CanvasEllipse,
3435 pieslice: Y.CanvasPieSlice
3439 * Returns a shape based on the id of its dom node.
3441 * @method getShapeById
3442 * @param {String} id Dom id of the shape's node attribute.
3445 getShapeById: function(id)
3447 var shape = this._shapes[id];
3452 * Allows for creating multiple shapes in order to batch appending and redraw operations.
3455 * @param {Function} method Method to execute.
3457 batch: function(method)
3459 var autoDraw = this.get("autoDraw");
3460 this.set("autoDraw", false);
3462 this.set("autoDraw", autoDraw);
3466 * Returns a document fragment to for attaching shapes.
3468 * @method _getDocFrag
3469 * @return DocumentFragment
3472 _getDocFrag: function()
3476 this._frag = DOCUMENT.createDocumentFragment();
3482 * Redraws all shapes.
3489 var autoSize = this.get("autoSize"),
3490 preserveAspectRatio = this.get("preserveAspectRatio"),
3491 box = this.get("resizeDown") ? this._getUpdatedContentBounds() : this._contentBounds,
3501 node = this.get("node");
3504 if(autoSize === "sizeContentToGraphic")
3506 contentWidth = box.right - box.left;
3507 contentHeight = box.bottom - box.top;
3508 w = parseFloat(Y_DOM.getComputedStyle(node, "width"));
3509 h = parseFloat(Y_DOM.getComputedStyle(node, "height"));
3510 matrix = new Y.Matrix();
3511 if(preserveAspectRatio === "none")
3513 xScale = w/contentWidth;
3514 yScale = h/contentHeight;
3518 if(contentWidth/contentHeight !== w/h)
3520 if(contentWidth * h/contentHeight > w)
3522 xScale = yScale = w/contentWidth;
3523 translateY = this._calculateTranslate(preserveAspectRatio.slice(5).toLowerCase(), contentHeight * w/contentWidth, h);
3527 xScale = yScale = h/contentHeight;
3528 translateX = this._calculateTranslate(preserveAspectRatio.slice(1, 4).toLowerCase(), contentWidth * h/contentHeight, w);
3532 Y_DOM.setStyle(node, "transformOrigin", "0% 0%");
3533 translateX = translateX - (box.left * xScale);
3534 translateY = translateY - (box.top * yScale);
3535 matrix.translate(translateX, translateY);
3536 matrix.scale(xScale, yScale);
3537 Y_DOM.setStyle(node, "transform", matrix.toCSSText());
3541 this.set("width", box.right);
3542 this.set("height", box.bottom);
3547 this._node.appendChild(this._frag);
3553 * Determines the value for either an x or y value to be used for the <code>translate</code> of the Graphic.
3555 * @method _calculateTranslate
3556 * @param {String} position The position for placement. Possible values are min, mid and max.
3557 * @param {Number} contentSize The total size of the content.
3558 * @param {Number} boundsSize The total size of the Graphic.
3562 _calculateTranslate: function(position, contentSize, boundsSize)
3564 var ratio = boundsSize - contentSize,
3569 coord = ratio * 0.5;
3582 * Adds a shape to the redraw queue and calculates the contentBounds. Used internally
3583 * by `Shape` instances.
3585 * @method addToRedrawQueue
3586 * @param Shape shape The shape instance to add to the queue
3589 addToRedrawQueue: function(shape)
3593 this._shapes[shape.get("id")] = shape;
3594 if(!this.get("resizeDown"))
3596 shapeBox = shape.getBounds();
3597 box = this._contentBounds;
3598 box.left = box.left < shapeBox.left ? box.left : shapeBox.left;
3599 box.top = box.top < shapeBox.top ? box.top : shapeBox.top;
3600 box.right = box.right > shapeBox.right ? box.right : shapeBox.right;
3601 box.bottom = box.bottom > shapeBox.bottom ? box.bottom : shapeBox.bottom;
3602 this._contentBounds = box;
3604 if(this.get("autoDraw"))
3611 * Recalculates and returns the `contentBounds` for the `Graphic` instance.
3613 * @method _getUpdatedContentBounds
3617 _getUpdatedContentBounds: function()
3622 queue = this._shapes,
3626 if(queue.hasOwnProperty(i))
3629 bounds = shape.getBounds();
3630 box.left = Y_LANG.isNumber(box.left) ? Math.min(box.left, bounds.left) : bounds.left;
3631 box.top = Y_LANG.isNumber(box.top) ? Math.min(box.top, bounds.top) : bounds.top;
3632 box.right = Y_LANG.isNumber(box.right) ? Math.max(box.right, bounds.right) : bounds.right;
3633 box.bottom = Y_LANG.isNumber(box.bottom) ? Math.max(box.bottom, bounds.bottom) : bounds.bottom;
3636 box.left = Y_LANG.isNumber(box.left) ? box.left : 0;
3637 box.top = Y_LANG.isNumber(box.top) ? box.top : 0;
3638 box.right = Y_LANG.isNumber(box.right) ? box.right : 0;
3639 box.bottom = Y_LANG.isNumber(box.bottom) ? box.bottom : 0;
3640 this._contentBounds = box;
3645 * Inserts shape on the top of the tree.
3648 * @param {CanvasShape} Shape to add.
3651 _toFront: function(shape)
3653 var contentNode = this.get("node");
3654 if(shape instanceof Y.CanvasShape)
3656 shape = shape.get("node");
3658 if(contentNode && shape)
3660 contentNode.appendChild(shape);
3665 * Inserts shape as the first child of the content node.
3668 * @param {CanvasShape} Shape to add.
3671 _toBack: function(shape)
3673 var contentNode = this.get("node"),
3675 if(shape instanceof Y.CanvasShape)
3677 shape = shape.get("node");
3679 if(contentNode && shape)
3681 targetNode = contentNode.firstChild;
3684 contentNode.insertBefore(shape, targetNode);
3688 contentNode.appendChild(shape);
3694 Y.CanvasGraphic = CanvasGraphic;
3697 }, '3.13.0', {"requires": ["graphics"]});