3 Copyright 2012 Yahoo! Inc. All rights reserved.
4 Licensed under the BSD License.
5 http://yuilibrary.com/license/
7 YUI.add('graphics-canvas', function (Y, NAME) {
9 var IMPLEMENTATION = "canvas",
11 SPLITPATHPATTERN = /[a-z][^a-z]*/ig,
12 SPLITARGSPATTERN = /[-]?[0-9]*[0-9|\.][0-9]*/g,
13 DOCUMENT = Y.config.doc,
15 AttributeLite = Y.AttributeLite,
25 PARSE_FLOAT = parseFloat,
26 IS_NUMBER = Y_LANG.isNumber,
28 TORGB = Y_Color.toRGB,
29 TOHEX = Y_Color.toHex,
30 _getClassName = Y.ClassNameManager.getClassName;
33 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> implementation of the <a href="Drawing.html">`Drawing`</a> class.
34 * `CanvasDrawing` is not intended to be used directly. Instead, use the <a href="Drawing.html">`Drawing`</a> class.
35 * If the browser lacks <a href="http://www.w3.org/TR/SVG/">SVG</a> capabilities but has
36 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> capabilities, the <a href="Drawing.html">`Drawing`</a>
37 * class will point to the `CanvasDrawing` class.
40 * @class CanvasDrawing
43 function CanvasDrawing()
47 CanvasDrawing.prototype = {
49 * Maps path to methods
51 * @property _pathSymbolToMethod
55 _pathSymbolToMethod: {
62 Q: "quadraticCurveTo",
63 q: "relativeQuadraticCurveTo",
69 * Current x position of the drawing.
78 * Current y position of the drqwing.
87 * Parses hex color string and alpha value to rgba
90 * @param {Object} val Color value to parse. Can be hex string, rgb or name.
91 * @param {Number} alpha Numeric value between 0 and 1 representing the alpha level.
94 _toRGBA: function(val, alpha) {
95 alpha = (alpha !== undefined) ? alpha : 1;
96 if (!Y_Color.re_RGB.test(val)) {
100 if(Y_Color.re_hex.exec(val)) {
102 PARSE_INT(RE.$1, 16),
103 PARSE_INT(RE.$2, 16),
105 ].join(',') + ',' + alpha + ')';
111 * Converts color to rgb format
114 * @param val Color value to convert.
117 _toRGB: function(val) {
122 * Sets the size of the graphics object.
125 * @param w {Number} width to set for the instance.
126 * @param h {Number} height to set for the instance.
129 setSize: function(w, h) {
130 if(this.get("autoSize"))
132 if(w > this.node.getAttribute("width"))
134 this.node.style.width = w + "px";
135 this.node.setAttribute("width", w);
137 if(h > this.node.getAttribute("height"))
139 this.node.style.height = h + "px";
140 this.node.setAttribute("height", h);
146 * Tracks coordinates. Used to calculate the start point of dashed lines.
148 * @method _updateCoords
149 * @param {Number} x x-coordinate
150 * @param {Number} y y-coordinate
153 _updateCoords: function(x, y)
155 this._xcoords.push(x);
156 this._ycoords.push(y);
162 * Clears the coordinate arrays. Called at the end of a drawing operation.
164 * @method _clearAndUpdateCoords
167 _clearAndUpdateCoords: function()
169 var x = this._xcoords.pop() || 0,
170 y = this._ycoords.pop() || 0;
171 this._updateCoords(x, y);
175 * Moves the shape's dom node.
177 * @method _updateNodePosition
180 _updateNodePosition: function()
182 var node = this.get("node"),
185 node.style.position = "absolute";
186 node.style.left = (x + this._left) + "px";
187 node.style.top = (y + this._top) + "px";
191 * Queues up a method to be executed when a shape redraws.
193 * @method _updateDrawingQueue
194 * @param {Array} val An array containing data that can be parsed into a method and arguments. The value at zero-index of the array is a string reference of
195 * the drawing method that will be called. All subsequent indices are argument for that method. For example, `lineTo(10, 100)` would be structured as:
196 * `["lineTo", 10, 100]`.
199 _updateDrawingQueue: function(val)
201 this._methods.push(val);
205 * Draws a line segment from the current drawing position to the specified x and y coordinates.
208 * @param {Number} point1 x-coordinate for the end point.
209 * @param {Number} point2 y-coordinate for the end point.
213 this._lineTo.apply(this, [Y.Array(arguments), false]);
217 * Draws a line segment from the current drawing position to the relative x and y coordinates.
220 * @param {Number} point1 x-coordinate for the end point.
221 * @param {Number} point2 y-coordinate for the end point.
223 relativeLineTo: function()
225 this._lineTo.apply(this, [Y.Array(arguments), true]);
229 * Implements lineTo methods.
232 * @param {Array} args The arguments to be used.
233 * @param {Boolean} relative Indicates whether or not to use relative coordinates.
236 _lineTo: function(args, relative)
238 var point1 = args[0],
243 wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0,
244 relativeX = relative ? parseFloat(this._currentX) : 0,
245 relativeY = relative ? parseFloat(this._currentY) : 0;
246 if(!this._lineToMethods)
248 this._lineToMethods = [];
250 len = args.length - 1;
251 if (typeof point1 === 'string' || typeof point1 === 'number') {
252 for (i = 0; i < len; i = i + 2) {
253 x = parseFloat(args[i]);
254 y = parseFloat(args[i + 1]);
257 this._updateDrawingQueue(["lineTo", x, y]);
258 this._trackSize(x - wt, y - wt);
259 this._trackSize(x + wt, y + wt);
260 this._updateCoords(x, y);
265 for (i = 0; i < len; i = i + 1)
267 x = parseFloat(args[i][0]);
268 y = parseFloat(args[i][1]);
269 this._updateDrawingQueue(["lineTo", x, y]);
270 this._lineToMethods[this._lineToMethods.length] = this._methods[this._methods.length - 1];
271 this._trackSize(x - wt, y - wt);
272 this._trackSize(x + wt, y + wt);
273 this._updateCoords(x, y);
276 this._drawingComplete = false;
281 * Moves the current drawing position to specified x and y coordinates.
284 * @param {Number} x x-coordinate for the end point.
285 * @param {Number} y y-coordinate for the end point.
289 this._moveTo.apply(this, [Y.Array(arguments), false]);
293 * Moves the current drawing position relative to specified x and y coordinates.
295 * @method relativeMoveTo
296 * @param {Number} x x-coordinate for the end point.
297 * @param {Number} y y-coordinate for the end point.
299 relativeMoveTo: function()
301 this._moveTo.apply(this, [Y.Array(arguments), true]);
305 * Implements moveTo methods.
308 * @param {Array} args The arguments to be used.
309 * @param {Boolean} relative Indicates whether or not to use relative coordinates.
312 _moveTo: function(args, relative) {
313 var wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0,
314 relativeX = relative ? parseFloat(this._currentX) : 0,
315 relativeY = relative ? parseFloat(this._currentY) : 0,
316 x = parseFloat(args[0]) + relativeX,
317 y = parseFloat(args[1]) + relativeY;
318 this._updateDrawingQueue(["moveTo", x, y]);
319 this._trackSize(x - wt, y - wt);
320 this._trackSize(x + wt, y + wt);
321 this._updateCoords(x, y);
322 this._drawingComplete = false;
327 * Draws a bezier curve.
330 * @param {Number} cp1x x-coordinate for the first control point.
331 * @param {Number} cp1y y-coordinate for the first control point.
332 * @param {Number} cp2x x-coordinate for the second control point.
333 * @param {Number} cp2y y-coordinate for the second control point.
334 * @param {Number} x x-coordinate for the end point.
335 * @param {Number} y y-coordinate for the end point.
337 curveTo: function() {
338 this._curveTo.apply(this, [Y.Array(arguments), false]);
342 * Draws a bezier curve relative to the current coordinates.
345 * @param {Number} cp1x x-coordinate for the first control point.
346 * @param {Number} cp1y y-coordinate for the first control point.
347 * @param {Number} cp2x x-coordinate for the second control point.
348 * @param {Number} cp2y y-coordinate for the second control point.
349 * @param {Number} x x-coordinate for the end point.
350 * @param {Number} y y-coordinate for the end point.
352 relativeCurveTo: function() {
353 this._curveTo.apply(this, [Y.Array(arguments), true]);
357 * Implements curveTo methods.
360 * @param {Array} args The arguments to be used.
361 * @param {Boolean} relative Indicates whether or not to use relative coordinates.
364 _curveTo: function(args, relative) {
380 relativeX = relative ? parseFloat(this._currentX) : 0,
381 relativeY = relative ? parseFloat(this._currentY) : 0;
382 len = args.length - 5;
383 for(i = 0; i < len; i = i + 6)
385 cp1x = parseFloat(args[i]) + relativeX;
386 cp1y = parseFloat(args[i + 1]) + relativeY;
387 cp2x = parseFloat(args[i + 2]) + relativeX;
388 cp2y = parseFloat(args[i + 3]) + relativeY;
389 x = parseFloat(args[i + 4]) + relativeX;
390 y = parseFloat(args[i + 5]) + relativeY;
391 this._updateDrawingQueue(["bezierCurveTo", cp1x, cp1y, cp2x, cp2y, x, y]);
392 this._drawingComplete = false;
393 right = Math.max(x, Math.max(cp1x, cp2x));
394 bottom = Math.max(y, Math.max(cp1y, cp2y));
395 left = Math.min(x, Math.min(cp1x, cp2x));
396 top = Math.min(y, Math.min(cp1y, cp2y));
397 w = Math.abs(right - left);
398 h = Math.abs(bottom - top);
399 pts = [[this._currentX, this._currentY] , [cp1x, cp1y], [cp2x, cp2y], [x, y]];
400 this._setCurveBoundingBox(pts, w, h);
407 * Draws a quadratic bezier curve.
409 * @method quadraticCurveTo
410 * @param {Number} cpx x-coordinate for the control point.
411 * @param {Number} cpy y-coordinate for the control point.
412 * @param {Number} x x-coordinate for the end point.
413 * @param {Number} y y-coordinate for the end point.
415 quadraticCurveTo: function() {
416 this._quadraticCurveTo.apply(this, [Y.Array(arguments), false]);
420 * Draws a quadratic bezier curve relative to the current position.
422 * @method relativeQuadraticCurveTo
423 * @param {Number} cpx x-coordinate for the control point.
424 * @param {Number} cpy y-coordinate for the control point.
425 * @param {Number} x x-coordinate for the end point.
426 * @param {Number} y y-coordinate for the end point.
428 relativeQuadraticCurveTo: function() {
429 this._quadraticCurveTo.apply(this, [Y.Array(arguments), true]);
433 * Implements quadraticCurveTo methods.
435 * @method _quadraticCurveTo
436 * @param {Array} args The arguments to be used.
437 * @param {Boolean} relative Indicates whether or not to use relative coordinates.
440 _quadraticCurveTo: function(args, relative) {
453 len = args.length - 3,
454 wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0,
455 relativeX = relative ? parseFloat(this._currentX) : 0,
456 relativeY = relative ? parseFloat(this._currentY) : 0;
457 for(i = 0; i < len; i = i + 4)
459 cpx = parseFloat(args[i]) + relativeX;
460 cpy = parseFloat(args[i + 1]) + relativeY;
461 x = parseFloat(args[i + 2]) + relativeX;
462 y = parseFloat(args[i + 3]) + relativeY;
463 this._drawingComplete = false;
464 right = Math.max(x, cpx);
465 bottom = Math.max(y, cpy);
466 left = Math.min(x, cpx);
467 top = Math.min(y, cpy);
468 w = Math.abs(right - left);
469 h = Math.abs(bottom - top);
470 pts = [[this._currentX, this._currentY] , [cpx, cpy], [x, y]];
471 this._setCurveBoundingBox(pts, w, h);
472 this._updateDrawingQueue(["quadraticCurveTo", cpx, cpy, x, y]);
473 this._updateCoords(x, y);
479 * Draws a circle. Used internally by `CanvasCircle` class.
482 * @param {Number} x y-coordinate
483 * @param {Number} y x-coordinate
484 * @param {Number} r radius
487 drawCircle: function(x, y, radius) {
489 endAngle = 2 * Math.PI,
490 wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0,
493 this._drawingComplete = false;
494 this._trackSize(x + circum, y + circum);
495 this._trackSize(x - wt, y - wt);
496 this._updateCoords(x, y);
497 this._updateDrawingQueue(["arc", x + radius, y + radius, radius, startAngle, endAngle, false]);
504 * @method drawDiamond
505 * @param {Number} x y-coordinate
506 * @param {Number} y x-coordinate
507 * @param {Number} width width
508 * @param {Number} height height
511 drawDiamond: function(x, y, width, height)
513 var midWidth = width * 0.5,
514 midHeight = height * 0.5;
515 this.moveTo(x + midWidth, y);
516 this.lineTo(x + width, y + midHeight);
517 this.lineTo(x + midWidth, y + height);
518 this.lineTo(x, y + midHeight);
519 this.lineTo(x + midWidth, y);
524 * Draws an ellipse. Used internally by `CanvasEllipse` class.
526 * @method drawEllipse
527 * @param {Number} x x-coordinate
528 * @param {Number} y y-coordinate
529 * @param {Number} w width
530 * @param {Number} h height
533 drawEllipse: function(x, y, w, h) {
535 theta = -(45/180) * Math.PI,
541 centerX = x + radius,
542 centerY = y + yRadius,
543 ax, ay, bx, by, cx, cy,
544 wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0;
546 ax = centerX + Math.cos(0) * radius;
547 ay = centerY + Math.sin(0) * yRadius;
549 for(i = 0; i < l; i++)
552 angleMid = angle - (theta / 2);
553 bx = centerX + Math.cos(angle) * radius;
554 by = centerY + Math.sin(angle) * yRadius;
555 cx = centerX + Math.cos(angleMid) * (radius / Math.cos(theta / 2));
556 cy = centerY + Math.sin(angleMid) * (yRadius / Math.cos(theta / 2));
557 this._updateDrawingQueue(["quadraticCurveTo", cx, cy, bx, by]);
559 this._trackSize(x + w + wt, y + h + wt);
560 this._trackSize(x - wt, y - wt);
561 this._updateCoords(x, y);
569 * @param {Number} x x-coordinate
570 * @param {Number} y y-coordinate
571 * @param {Number} w width
572 * @param {Number} h height
574 drawRect: function(x, y, w, h) {
575 var wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0;
576 this._drawingComplete = false;
578 this.lineTo(x + w, y);
579 this.lineTo(x + w, y + h);
580 this.lineTo(x, y + h);
586 * Draws a rectangle with rounded corners.
589 * @param {Number} x x-coordinate
590 * @param {Number} y y-coordinate
591 * @param {Number} w width
592 * @param {Number} h height
593 * @param {Number} ew width of the ellipse used to draw the rounded corners
594 * @param {Number} eh height of the ellipse used to draw the rounded corners
596 drawRoundRect: function(x, y, w, h, ew, eh) {
597 var wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0;
598 this._drawingComplete = false;
599 this.moveTo( x, y + eh);
600 this.lineTo(x, y + h - eh);
601 this.quadraticCurveTo(x, y + h, x + ew, y + h);
602 this.lineTo(x + w - ew, y + h);
603 this.quadraticCurveTo(x + w, y + h, x + w, y + h - eh);
604 this.lineTo(x + w, y + eh);
605 this.quadraticCurveTo(x + w, y, x + w - ew, y);
606 this.lineTo(x + ew, y);
607 this.quadraticCurveTo(x, y, x, y + eh);
615 * @param {Number} x x-coordinate of the wedge's center point
616 * @param {Number} y y-coordinate of the wedge's center point
617 * @param {Number} startAngle starting angle in degrees
618 * @param {Number} arc sweep of the wedge. Negative values draw clockwise.
619 * @param {Number} radius radius of wedge. If [optional] yRadius is defined, then radius is the x radius.
620 * @param {Number} yRadius [optional] y radius for wedge.
623 drawWedge: function(x, y, startAngle, arc, radius, yRadius)
625 var wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0,
638 yRadius = yRadius || radius;
640 this._drawingComplete = false;
641 // move to x,y position
642 this._updateDrawingQueue(["moveTo", x, y]);
644 yRadius = yRadius || radius;
646 // limit sweep to reasonable numbers
647 if(Math.abs(arc) > 360)
652 // First we calculate how many segments are needed
654 segs = Math.ceil(Math.abs(arc) / 45);
656 // Now calculate the sweep of each segment.
657 segAngle = arc / segs;
659 // The math requires radians rather than degrees. To convert from degrees
660 // use the formula (degrees/180)*Math.PI to get radians.
661 theta = -(segAngle / 180) * Math.PI;
663 // convert angle startAngle to radians
664 angle = (startAngle / 180) * Math.PI;
666 // draw the curve in segments no larger than 45 degrees.
669 // draw a line from the center to the start of the curve
670 ax = x + Math.cos(startAngle / 180 * Math.PI) * radius;
671 ay = y + Math.sin(startAngle / 180 * Math.PI) * yRadius;
673 // Loop for drawing curve segments
674 for(i = 0; i < segs; ++i)
677 angleMid = angle - (theta / 2);
678 bx = x + Math.cos(angle) * radius;
679 by = y + Math.sin(angle) * yRadius;
680 cx = x + Math.cos(angleMid) * (radius / Math.cos(theta / 2));
681 cy = y + Math.sin(angleMid) * (yRadius / Math.cos(theta / 2));
682 this._updateDrawingQueue(["quadraticCurveTo", cx, cy, bx, by]);
684 // close the wedge by drawing a line to the center
685 this._updateDrawingQueue(["lineTo", x, y]);
687 this._trackSize(-wt , -wt);
688 this._trackSize((radius * 2) + wt, (radius * 2) + wt);
693 * Completes a drawing operation.
703 * Ends a fill and stroke
707 closePath: function()
709 this._updateDrawingQueue(["closePath"]);
710 this._updateDrawingQueue(["beginPath"]);
714 * Clears the graphics object.
720 * Returns a linear gradient fill
722 * @method _getLinearGradient
723 * @return CanvasGradient
726 _getLinearGradient: function() {
727 var isNumber = Y.Lang.isNumber,
728 fill = this.get("fill"),
738 w = this.get("width"),
739 h = this.get("height"),
740 r = fill.rotation || 0,
745 radCon = Math.PI/180,
746 tanRadians = parseFloat(parseFloat(Math.tan(r * radCon)).toFixed(8));
747 if(Math.abs(tanRadians) * w/2 >= h/2)
759 x1 = cx - ((cy - y1)/tanRadians);
760 x2 = cx - ((cy - y2)/tanRadians);
764 if(r > 90 && r < 270)
774 y1 = ((tanRadians * (cx - x1)) - cy) * -1;
775 y2 = ((tanRadians * (cx - x2)) - cy) * -1;
777 gradient = this._context.createLinearGradient(x1, y1, x2, y2);
778 for(i = 0; i < len; ++i)
781 opacity = stop.opacity;
783 offset = stop.offset;
784 if(isNumber(opacity))
786 opacity = Math.max(0, Math.min(1, opacity));
787 color = this._toRGBA(color, opacity);
791 color = TORGB(color);
793 offset = stop.offset || i/(len - 1);
794 gradient.addColorStop(offset, color);
800 * Returns a radial gradient fill
802 * @method _getRadialGradient
803 * @return CanvasGradient
806 _getRadialGradient: function() {
807 var isNumber = Y.Lang.isNumber,
808 fill = this.get("fill"),
821 w = this.get("width"),
822 h = this.get("height"),
835 d = Math.sqrt( Math.pow(Math.abs(xc - x1), 2) + Math.pow(Math.abs(yc - y1), 2) );
839 //hack. gradient won't show if it is exactly on the edge of the arc
844 xn = (x1 - xc)/ratio;
845 yn = (y1 - yc)/ratio;
846 xn = xn > 0 ? Math.floor(xn) : Math.ceil(xn);
847 yn = yn > 0 ? Math.floor(yn) : Math.ceil(yn);
852 //If the gradient radius is greater than the circle's, adjusting the radius stretches the gradient properly.
853 //If the gradient radius is less than the circle's, adjusting the radius of the gradient will not work.
854 //Instead, adjust the color stops to reflect the smaller radius.
857 gradient = this._context.createRadialGradient(x1, y1, r, x2, y2, r * w);
862 gradient = this._context.createRadialGradient(x1, y1, r, x2, y2, w/2);
863 stopMultiplier = r * 2;
865 for(i = 0; i < len; ++i)
868 opacity = stop.opacity;
870 offset = stop.offset;
871 if(isNumber(opacity))
873 opacity = Math.max(0, Math.min(1, opacity));
874 color = this._toRGBA(color, opacity);
878 color = TORGB(color);
880 offset = stop.offset || i/(len - 1);
881 offset *= stopMultiplier;
884 gradient.addColorStop(offset, color);
897 _initProps: function() {
899 this._lineToMethods = [];
913 * Indicates a drawing has completed.
915 * @property _drawingComplete
919 _drawingComplete: false,
922 * Creates canvas element
924 * @method _createGraphic
925 * @return HTMLCanvasElement
928 _createGraphic: function(config) {
929 var graphic = Y.config.doc.createElement('canvas');
934 * Returns the points on a curve
936 * @method getBezierData
937 * @param Array points Array containing the begin, end and control points of a curve.
938 * @param Number t The value for incrementing the next set of points.
942 getBezierData: function(points, t) {
943 var n = points.length,
948 for (i = 0; i < n; ++i){
949 tmp[i] = [points[i][0], points[i][1]]; // save input
952 for (j = 1; j < n; ++j) {
953 for (i = 0; i < n - j; ++i) {
954 tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0];
955 tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1];
958 return [ tmp[0][0], tmp[0][1] ];
962 * Calculates the bounding box for a curve
964 * @method _setCurveBoundingBox
965 * @param Array pts Array containing points for start, end and control points of a curve.
966 * @param Number w Width used to calculate the number of points to describe the curve.
967 * @param Number h Height used to calculate the number of points to describe the curve.
970 _setCurveBoundingBox: function(pts, w, h)
973 left = this._currentX,
975 top = this._currentY,
977 len = Math.round(Math.sqrt((w * w) + (h * h))),
979 wt = this._stroke && this._strokeWeight ? this._strokeWeight : 0,
981 for(i = 0; i < len; ++i)
983 xy = this.getBezierData(pts, t * i);
984 left = isNaN(left) ? xy[0] : Math.min(xy[0], left);
985 right = isNaN(right) ? xy[0] : Math.max(xy[0], right);
986 top = isNaN(top) ? xy[1] : Math.min(xy[1], top);
987 bottom = isNaN(bottom) ? xy[1] : Math.max(xy[1], bottom);
989 left = Math.round(left * 10)/10;
990 right = Math.round(right * 10)/10;
991 top = Math.round(top * 10)/10;
992 bottom = Math.round(bottom * 10)/10;
993 this._trackSize(right + wt, bottom + wt);
994 this._trackSize(left - wt, top - wt);
998 * Updates the size of the graphics object
1000 * @method _trackSize
1001 * @param {Number} w width
1002 * @param {Number} h height
1005 _trackSize: function(w, h) {
1006 if (w > this._right) {
1017 if (h > this._bottom)
1021 this._width = this._right - this._left;
1022 this._height = this._bottom - this._top;
1025 Y.CanvasDrawing = CanvasDrawing;
1027 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> implementation of the <a href="Shape.html">`Shape`</a> class.
1028 * `CanvasShape` is not intended to be used directly. Instead, use the <a href="Shape.html">`Shape`</a> class.
1029 * If the browser lacks <a href="http://www.w3.org/TR/SVG/">SVG</a> capabilities but has
1030 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> capabilities, the <a href="Shape.html">`Shape`</a>
1031 * class will point to the `CanvasShape` class.
1034 * @class CanvasShape
1037 CanvasShape = function(cfg)
1039 this._transforms = [];
1040 this.matrix = new Y.Matrix();
1041 CanvasShape.superclass.constructor.apply(this, arguments);
1044 CanvasShape.NAME = "shape";
1046 Y.extend(CanvasShape, Y.GraphicBase, Y.mix({
1048 * Init method, invoked during construction.
1049 * Calls `initializer` method.
1056 this.initializer.apply(this, arguments);
1060 * Initializes the shape
1063 * @method _initialize
1065 initializer: function(cfg)
1068 graphic = cfg.graphic,
1069 data = this.get("data");
1072 host._xcoords = [0];
1073 host._ycoords = [0];
1076 this._setGraphic(graphic);
1080 host._parsePathData(data);
1082 host._updateHandler();
1086 * Set the Graphic instance for the shape.
1088 * @method _setGraphic
1089 * @param {Graphic | Node | HTMLElement | String} render This param is used to determine the graphic instance. If it is a `Graphic` instance, it will be assigned
1090 * to the `graphic` attribute. Otherwise, a new Graphic instance will be created and rendered into the dom element that the render represents.
1093 _setGraphic: function(render)
1096 if(render instanceof Y.CanvasGraphic)
1098 this._graphic = render;
1102 render = Y.one(render);
1103 graphic = new Y.CanvasGraphic({
1106 graphic._appendShape(this);
1107 this._graphic = graphic;
1112 * Add a class name to each node.
1115 * @param {String} className the class name to add to the node's class attribute
1117 addClass: function(className)
1119 var node = Y.one(this.get("node"));
1120 node.addClass(className);
1124 * Removes a class name from each node.
1126 * @method removeClass
1127 * @param {String} className the class name to remove from the node's class attribute
1129 removeClass: function(className)
1131 var node = Y.one(this.get("node"));
1132 node.removeClass(className);
1136 * Gets the current position of the node in page coordinates.
1139 * @return Array The XY position of the shape.
1143 var graphic = this.get("graphic"),
1144 parentXY = graphic.getXY(),
1147 return [parentXY[0] + x, parentXY[1] + y];
1151 * Set the position of the shape in page coordinates, regardless of how the node is positioned.
1154 * @param {Array} Contains X & Y values for new position (coordinates are page-based)
1158 var graphic = this.get("graphic"),
1159 parentXY = graphic.getXY(),
1160 x = xy[0] - parentXY[0],
1161 y = xy[1] - parentXY[1];
1164 this._updateNodePosition(x, y);
1168 * Determines whether the node is an ancestor of another HTML element in the DOM hierarchy.
1171 * @param {CanvasShape | HTMLElement} needle The possible node or descendent
1172 * @return Boolean Whether or not this shape is the needle or its ancestor.
1174 contains: function(needle)
1176 return needle === Y.one(this.node);
1180 * Test if the supplied node matches the supplied selector.
1183 * @param {String} selector The CSS selector to test against.
1184 * @return Boolean Wheter or not the shape matches the selector.
1186 test: function(selector)
1188 return Y.one(this.get("node")).test(selector);
1189 //return Y.Selector.test(this.node, selector);
1193 * Compares nodes to determine if they match.
1194 * Node instances can be compared to each other and/or HTMLElements.
1196 * @param {HTMLElement | Node} refNode The reference node to compare to the node.
1197 * @return {Boolean} True if the nodes match, false if they do not.
1199 compareTo: function(refNode) {
1200 var node = this.node;
1201 return node === refNode;
1205 * Value function for fill attribute
1207 * @method _getDefaultFill
1211 _getDefaultFill: function() {
1224 * Value function for stroke attribute
1226 * @method _getDefaultStroke
1230 _getDefaultStroke: function()
1241 * Left edge of the path
1250 * Right edge of the path
1259 * Top edge of the path
1268 * Bottom edge of the path
1277 * Creates the dom node for the shape.
1279 * @method createNode
1280 * @return HTMLElement
1283 createNode: function()
1286 node = Y.config.doc.createElement('canvas'),
1287 id = host.get("id"),
1288 concat = host._camelCaseConcat,
1290 host._context = node.getContext('2d');
1291 node.setAttribute("overflow", "visible");
1292 node.style.overflow = "visible";
1293 if(!host.get("visible"))
1295 node.style.visibility = "hidden";
1297 node.setAttribute("id", id);
1300 host.addClass(_getClassName(SHAPE) + " " + _getClassName(concat(IMPLEMENTATION, SHAPE)) + " " + _getClassName(name) + " " + _getClassName(concat(IMPLEMENTATION, name)));
1304 * Overrides default `on` method. Checks to see if its a dom interaction event. If so,
1305 * return an event attached to the `node` element. If not, return the normal functionality.
1308 * @param {String} type event type
1309 * @param {Object} callback function
1312 on: function(type, fn)
1314 if(Y.Node.DOM_EVENTS[type])
1316 return Y.one("#" + this.get("id")).on(type, fn);
1318 return Y.on.apply(this, arguments);
1322 * Adds a stroke to the shape node.
1324 * @method _strokeChangeHandler
1325 * @param {Object} stroke Properties of the `stroke` attribute.
1328 _setStrokeProps: function(stroke)
1338 color = stroke.color;
1339 weight = PARSE_FLOAT(stroke.weight);
1340 opacity = PARSE_FLOAT(stroke.opacity);
1341 linejoin = stroke.linejoin || "round";
1342 linecap = stroke.linecap || "butt";
1343 dashstyle = stroke.dashstyle;
1344 this._miterlimit = null;
1345 this._dashstyle = (dashstyle && Y.Lang.isArray(dashstyle) && dashstyle.length > 1) ? dashstyle : null;
1346 this._strokeWeight = weight;
1348 if (IS_NUMBER(weight) && weight > 0)
1356 if (IS_NUMBER(opacity)) {
1357 this._strokeStyle = this._toRGBA(color, opacity);
1361 this._strokeStyle = color;
1363 this._linecap = linecap;
1364 if(linejoin == "round" || linejoin == "bevel")
1366 this._linejoin = linejoin;
1370 linejoin = parseInt(linejoin, 10);
1371 if(IS_NUMBER(linejoin))
1373 this._miterlimit = Math.max(linejoin, 1);
1374 this._linejoin = "miter";
1385 * Sets the value of an attribute.
1388 * @param {String|Object} name The name of the attribute. Alternatively, an object of key value pairs can
1389 * be passed in to set multiple attributes at once.
1390 * @param {Any} value The value to set the attribute to. This value is ignored if an object is received as
1397 AttributeLite.prototype.set.apply(host, arguments);
1398 if(host.initialized)
1400 host._updateHandler();
1405 * Adds a fill to the shape node.
1407 * @method _setFillProps
1408 * @param {Object} fill Properties of the `fill` attribute.
1411 _setFillProps: function(fill)
1413 var isNumber = IS_NUMBER,
1421 if(type == "linear" || type == "radial")
1423 this._fillType = type;
1427 opacity = fill.opacity;
1428 if (isNumber(opacity))
1430 opacity = Math.max(0, Math.min(1, opacity));
1431 color = this._toRGBA(color, opacity);
1435 color = TORGB(color);
1438 this._fillColor = color;
1439 this._fillType = 'solid';
1443 this._fillColor = null;
1448 this._fillType = null;
1449 this._fillColor = null;
1454 * Specifies a 2d translation.
1457 * @param {Number} x The value to transate on the x-axis.
1458 * @param {Number} y The value to translate on the y-axis.
1460 translate: function(x, y)
1462 this._translateX += x;
1463 this._translateY += y;
1464 this._addTransform("translate", arguments);
1468 * Translates the shape along the x-axis. When translating x and y coordinates,
1469 * use the `translate` method.
1471 * @method translateX
1472 * @param {Number} x The value to translate.
1474 translateX: function(x)
1476 this._translateX += x;
1477 this._addTransform("translateX", arguments);
1481 * Performs a translate on the y-coordinate. When translating x and y coordinates,
1482 * use the `translate` method.
1484 * @method translateY
1485 * @param {Number} y The value to translate.
1487 translateY: function(y)
1489 this._translateY += y;
1490 this._addTransform("translateY", arguments);
1494 * Skews the shape around the x-axis and y-axis.
1497 * @param {Number} x The value to skew on the x-axis.
1498 * @param {Number} y The value to skew on the y-axis.
1500 skew: function(x, y)
1502 this._addTransform("skew", arguments);
1506 * Skews the shape around the x-axis.
1509 * @param {Number} x x-coordinate
1513 this._addTransform("skewX", arguments);
1517 * Skews the shape around the y-axis.
1520 * @param {Number} y y-coordinate
1524 this._addTransform("skewY", arguments);
1528 * Rotates the shape clockwise around it transformOrigin.
1531 * @param {Number} deg The degree of the rotation.
1533 rotate: function(deg)
1535 this._rotation = deg;
1536 this._addTransform("rotate", arguments);
1540 * Specifies a 2d scaling operation.
1543 * @param {Number} val
1545 scale: function(x, y)
1547 this._addTransform("scale", arguments);
1551 * Storage for `rotation` atribute.
1553 * @property _rotation
1560 * Storage for the transform attribute.
1562 * @property _transform
1569 * Adds a transform to the shape.
1571 * @method _addTransform
1572 * @param {String} type The transform being applied.
1573 * @param {Array} args The arguments for the transform.
1576 _addTransform: function(type, args)
1578 args = Y.Array(args);
1579 this._transform = Y_LANG.trim(this._transform + " " + type + "(" + args.join(", ") + ")");
1581 this._transforms.push(args);
1582 if(this.initialized)
1584 this._updateTransform();
1589 * Applies all transforms.
1591 * @method _updateTransform
1594 _updateTransform: function()
1596 var node = this.node,
1599 transformOrigin = this.get("transformOrigin"),
1600 matrix = this.matrix,
1602 len = this._transforms.length;
1604 if(this._transforms && this._transforms.length > 0)
1606 for(i = 0; i < len; ++i)
1608 key = this._transforms[i].shift();
1611 matrix[key].apply(matrix, this._transforms[i]);
1614 transform = matrix.toCSSText();
1617 this._graphic.addToRedrawQueue(this);
1618 transformOrigin = (100 * transformOrigin[0]) + "% " + (100 * transformOrigin[1]) + "%";
1619 Y_DOM.setStyle(node, "transformOrigin", transformOrigin);
1622 Y_DOM.setStyle(node, "transform", transform);
1624 this._transforms = [];
1628 * Updates `Shape` based on attribute changes.
1630 * @method _updateHandler
1633 _updateHandler: function()
1636 this._updateTransform();
1640 * Updates the shape.
1647 var node = this.node;
1650 node.style.left = this.get("x") + "px";
1651 node.style.top = this.get("y") + "px";
1655 * Completes a shape or drawing
1657 * @method _closePath
1660 _closePath: function()
1666 var node = this.get("node"),
1667 w = this._right - this._left,
1668 h = this._bottom - this._top,
1669 context = this._context,
1671 cachedMethods = this._methods.concat(),
1678 this._context.clearRect(0, 0, node.width, node.height);
1681 len = cachedMethods.length;
1686 for(i = 0; i < len; ++i)
1688 methods[i] = cachedMethods[i].concat();
1690 argsLen = (args[0] == "quadraticCurveTo" || args[0] == "bezierCurveTo") ? args.length : 3;
1691 for(j = 1; j < argsLen; ++j)
1695 args[j] = args[j] - this._top;
1699 args[j] = args[j] - this._left;
1703 node.setAttribute("width", Math.min(w, 2000));
1704 node.setAttribute("height", Math.min(2000, h));
1705 context.beginPath();
1706 for(i = 0; i < len; ++i)
1708 args = methods[i].concat();
1709 if(args && args.length > 0)
1711 method = args.shift();
1714 if(method == "closePath")
1716 context.closePath();
1717 this._strokeAndFill(context);
1719 else if(method && method == "lineTo" && this._dashstyle)
1721 args.unshift(this._xcoords[i] - this._left, this._ycoords[i] - this._top);
1722 this._drawDashedLine.apply(this, args);
1726 context[method].apply(context, args);
1732 this._strokeAndFill(context);
1733 this._drawingComplete = true;
1734 this._clearAndUpdateCoords();
1735 this._updateNodePosition();
1736 this._methods = cachedMethods;
1741 * Completes a stroke and/or fill operation on the context.
1743 * @method _strokeAndFill
1744 * @param {Context} Reference to the context element of the canvas instance.
1747 _strokeAndFill: function(context)
1751 if(this._fillType == "linear")
1753 context.fillStyle = this._getLinearGradient();
1755 else if(this._fillType == "radial")
1757 context.fillStyle = this._getRadialGradient();
1761 context.fillStyle = this._fillColor;
1763 context.closePath();
1768 if(this._strokeWeight)
1770 context.lineWidth = this._strokeWeight;
1772 context.lineCap = this._linecap;
1773 context.lineJoin = this._linejoin;
1774 if(this._miterlimit)
1776 context.miterLimit = this._miterlimit;
1778 context.strokeStyle = this._strokeStyle;
1784 * Draws a dashed line between two points.
1786 * @method _drawDashedLine
1787 * @param {Number} xStart The x position of the start of the line
1788 * @param {Number} yStart The y position of the start of the line
1789 * @param {Number} xEnd The x position of the end of the line
1790 * @param {Number} yEnd The y position of the end of the line
1793 _drawDashedLine: function(xStart, yStart, xEnd, yEnd)
1795 var context = this._context,
1796 dashsize = this._dashstyle[0],
1797 gapsize = this._dashstyle[1],
1798 segmentLength = dashsize + gapsize,
1799 xDelta = xEnd - xStart,
1800 yDelta = yEnd - yStart,
1801 delta = Math.sqrt(Math.pow(xDelta, 2) + Math.pow(yDelta, 2)),
1802 segmentCount = Math.floor(Math.abs(delta / segmentLength)),
1803 radians = Math.atan2(yDelta, xDelta),
1807 xDelta = Math.cos(radians) * segmentLength;
1808 yDelta = Math.sin(radians) * segmentLength;
1810 for(i = 0; i < segmentCount; ++i)
1812 context.moveTo(xCurrent, yCurrent);
1813 context.lineTo(xCurrent + Math.cos(radians) * dashsize, yCurrent + Math.sin(radians) * dashsize);
1818 context.moveTo(xCurrent, yCurrent);
1819 delta = Math.sqrt((xEnd - xCurrent) * (xEnd - xCurrent) + (yEnd - yCurrent) * (yEnd - yCurrent));
1821 if(delta > dashsize)
1823 context.lineTo(xCurrent + Math.cos(radians) * dashsize, yCurrent + Math.sin(radians) * dashsize);
1827 context.lineTo(xCurrent + Math.cos(radians) * delta, yCurrent + Math.sin(radians) * delta);
1830 context.moveTo(xEnd, yEnd);
1833 //This should move to CanvasDrawing class.
1834 //Currently docmented in CanvasDrawing class.
1839 this._context.clearRect(0, 0, this.node.width, this.node.height);
1845 * Returns the bounds for a shape.
1847 * Calculates the a new bounding box from the original corner coordinates (base on size and position) and the transform matrix.
1848 * The calculated bounding box is used by the graphic instance to calculate its viewBox.
1853 getBounds: function()
1855 var type = this._type,
1856 w = this.get("width"),
1857 h = this.get("height"),
1864 w = this._right - this._left;
1865 h = this._bottom - this._top;
1867 return this._getContentRect(w, h, x, y);
1871 * Calculates the bounding box for the shape.
1873 * @method _getContentRect
1874 * @param {Number} w width of the shape
1875 * @param {Number} h height of the shape
1876 * @param {Number} x x-coordinate of the shape
1877 * @param {Number} y y-coordinate of the shape
1880 _getContentRect: function(w, h, x, y)
1882 var transformOrigin = this.get("transformOrigin"),
1883 transformX = transformOrigin[0] * w,
1884 transformY = transformOrigin[1] * h,
1885 transforms = this.matrix.getTransformArray(this.get("transform")),
1886 matrix = new Y.Matrix(),
1888 len = transforms.length,
1892 if(this._type == "path")
1894 transformX = transformX + x;
1895 transformY = transformY + y;
1897 transformX = !isNaN(transformX) ? transformX : 0;
1898 transformY = !isNaN(transformY) ? transformY : 0;
1899 matrix.translate(transformX, transformY);
1900 for(i = 0; i < len; i = i + 1)
1902 transform = transforms[i];
1903 key = transform.shift();
1906 matrix[key].apply(matrix, transform);
1909 matrix.translate(-transformX, -transformY);
1910 contentRect = matrix.getContentRect(w, h, x, y);
1915 * Places the shape above all other shapes.
1921 var graphic = this.get("graphic");
1924 graphic._toFront(this);
1929 * Places the shape underneath all other shapes.
1935 var graphic = this.get("graphic");
1938 graphic._toBack(this);
1943 * Parses path data string and call mapped methods.
1945 * @method _parsePathData
1946 * @param {String} val The path data
1949 _parsePathData: function(val)
1954 commandArray = Y.Lang.trim(val.match(SPLITPATHPATTERN)),
1958 symbolToMethod = this._pathSymbolToMethod;
1962 len = commandArray.length || 0;
1963 for(i = 0; i < len; i = i + 1)
1965 str = commandArray[i];
1966 methodSymbol = str.substr(0, 1);
1967 args = str.substr(1).match(SPLITARGSPATTERN);
1968 method = symbolToMethod[methodSymbol];
1973 this[method].apply(this, args);
1977 this[method].apply(this);
1986 * Destroys the shape instance.
1992 var graphic = this.get("graphic");
1995 graphic.removeShape(this);
2004 * Implementation for shape destruction
2009 _destroy: function()
2013 Y.one(this.node).remove(true);
2014 this._context = null;
2018 }, Y.CanvasDrawing.prototype));
2020 CanvasShape.ATTRS = {
2022 * 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
2023 * fraction of the shape's corresponding bounding box dimension. The default value is [0.5, 0.5].
2025 * @config transformOrigin
2036 * <p>A string containing, in order, transform operations applied to the shape instance. The `transform` string can contain the following values:
2039 * <dt>rotate</dt><dd>Rotates the shape clockwise around it transformOrigin.</dd>
2040 * <dt>translate</dt><dd>Specifies a 2d translation.</dd>
2041 * <dt>skew</dt><dd>Skews the shape around the x-axis and y-axis.</dd>
2042 * <dt>scale</dt><dd>Specifies a 2d scaling operation.</dd>
2043 * <dt>translateX</dt><dd>Translates the shape along the x-axis.</dd>
2044 * <dt>translateY</dt><dd>Translates the shape along the y-axis.</dd>
2045 * <dt>skewX</dt><dd>Skews the shape around the x-axis.</dd>
2046 * <dt>skewY</dt><dd>Skews the shape around the y-axis.</dd>
2047 * <dt>matrix</dt><dd>Specifies a 2D transformation matrix comprised of the specified six values.</dd>
2050 * <p>Applying transforms through the transform attribute will reset the transform matrix and apply a new transform. The shape class also contains corresponding methods for each transform
2051 * that will apply the transform to the current matrix. The below code illustrates how you might use the `transform` attribute to instantiate a recangle with a rotation of 45 degrees.</p>
2052 var myRect = new Y.Rect({
2056 transform: "rotate(45)"
2058 * <p>The code below would apply `translate` and `rotate` to an existing shape.</p>
2060 myRect.set("transform", "translate(40, 50) rotate(45)");
2065 setter: function(val)
2068 this._transforms = this.matrix.getTransformArray(val);
2069 this._transform = val;
2075 return this._transform;
2080 * Dom node for the shape
2096 * Unique id for class instance.
2107 setter: function(val)
2109 var node = this.node;
2112 node.setAttribute("id", val);
2119 * Indicates the width of the shape
2129 * Indicates the height of the shape
2139 * Indicates the x position of shape.
2149 * Indicates the y position of shape.
2159 * Indicates whether the shape is visible.
2167 setter: function(val){
2168 var node = this.get("node"),
2169 visibility = val ? "visible" : "hidden";
2172 node.style.visibility = visibility;
2179 * Contains information about the fill of the shape.
2181 * <dt>color</dt><dd>The color of the fill.</dd>
2182 * <dt>opacity</dt><dd>Number between 0 and 1 that indicates the opacity of the fill. The default value is 1.</dd>
2183 * <dt>type</dt><dd>Type of fill.
2185 * <dt>solid</dt><dd>Solid single color fill. (default)</dd>
2186 * <dt>linear</dt><dd>Linear gradient fill.</dd>
2187 * <dt>radial</dt><dd>Radial gradient fill.</dd>
2191 * <p>If a `linear` or `radial` is specified as the fill type. The following additional property is used:
2193 * <dt>stops</dt><dd>An array of objects containing the following properties:
2195 * <dt>color</dt><dd>The color of the stop.</dd>
2196 * <dt>opacity</dt><dd>Number between 0 and 1 that indicates the opacity of the stop. The default value is 1. Note: No effect for IE 6 - 8</dd>
2197 * <dt>offset</dt><dd>Number between 0 and 1 indicating where the color stop is positioned.</dd>
2200 * <p>Linear gradients also have the following property:</p>
2201 * <dt>rotation</dt><dd>Linear gradients flow left to right by default. The rotation property allows you to change the flow by rotation. (e.g. A rotation of 180 would make the gradient pain from right to left.)</dd>
2202 * <p>Radial gradients have the following additional properties:</p>
2203 * <dt>r</dt><dd>Radius of the gradient circle.</dd>
2204 * <dt>fx</dt><dd>Focal point x-coordinate of the gradient.</dd>
2205 * <dt>fy</dt><dd>Focal point y-coordinate of the gradient.</dd>
2207 * <p>The corresponding `SVGShape` class implements the following additional properties.</p>
2210 * <p>The x-coordinate of the center of the gradient circle. Determines where the color stop begins. The default value 0.5.</p>
2213 * <p>The y-coordinate of the center of the gradient circle. Determines where the color stop begins. The default value 0.5.</p>
2216 * <p>These properties are not currently implemented in `CanvasShape` or `VMLShape`.</p>
2222 valueFn: "_getDefaultFill",
2224 setter: function(val)
2227 tmpl = this.get("fill") || this._getDefaultFill();
2228 fill = (val) ? Y.merge(tmpl, val) : null;
2229 if(fill && fill.color)
2231 if(fill.color === undefined || fill.color == "none")
2236 this._setFillProps(fill);
2242 * Contains information about the stroke of the shape.
2244 * <dt>color</dt><dd>The color of the stroke.</dd>
2245 * <dt>weight</dt><dd>Number that indicates the width of the stroke.</dd>
2246 * <dt>opacity</dt><dd>Number between 0 and 1 that indicates the opacity of the stroke. The default value is 1.</dd>
2247 * <dt>dashstyle</dt>Indicates whether to draw a dashed stroke. When set to "none", a solid stroke is drawn. When set to an array, the first index indicates the
2248 * length of the dash. The second index indicates the length of gap.
2249 * <dt>linecap</dt><dd>Specifies the linecap for the stroke. The following values can be specified:
2251 * <dt>butt (default)</dt><dd>Specifies a butt linecap.</dd>
2252 * <dt>square</dt><dd>Specifies a sqare linecap.</dd>
2253 * <dt>round</dt><dd>Specifies a round linecap.</dd>
2256 * <dt>linejoin</dt><dd>Specifies a linejoin for the stroke. The following values can be specified:
2258 * <dt>round (default)</dt><dd>Specifies that the linejoin will be round.</dd>
2259 * <dt>bevel</dt><dd>Specifies a bevel for the linejoin.</dd>
2260 * <dt>miter limit</dt><dd>An integer specifying the miter limit of a miter linejoin. If you want to specify a linejoin of miter, you simply specify the limit as opposed to having
2261 * separate miter and miter limit values.</dd>
2270 valueFn: "_getDefaultStroke",
2272 setter: function(val)
2274 var tmpl = this.get("stroke") || this._getDefaultStroke(),
2276 if(val && val.hasOwnProperty("weight"))
2278 wt = parseInt(val.weight, 10);
2284 val = (val) ? Y.merge(tmpl, val) : null;
2285 this._setStrokeProps(val);
2290 //Not used. Remove in future.
2295 // Only implemented in SVG
2296 // Determines whether the instance will receive mouse events.
2298 // @config pointerEvents
2302 value: "visiblePainted"
2306 * Represents an SVG Path string. This will be parsed and added to shape's API to represent the SVG data across all implementations. Note that when using VML or SVG
2307 * implementations, part of this content will be added to the DOM using respective VML/SVG attributes. If your content comes from an untrusted source, you will need
2308 * to ensure that no malicious code is included in that content.
2314 setter: function(val)
2316 if(this.get("node"))
2318 this._parsePathData(val);
2325 * Reference to the container Graphic.
2335 return this._graphic;
2339 Y.CanvasShape = CanvasShape;
2341 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> implementation of the <a href="Path.html">`Path`</a> class.
2342 * `CanvasPath` is not intended to be used directly. Instead, use the <a href="Path.html">`Path`</a> class.
2343 * If the browser lacks <a href="http://www.w3.org/TR/SVG/">SVG</a> capabilities but has
2344 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> capabilities, the <a href="Path.html">`Path`</a>
2345 * class will point to the `CanvasPath` class.
2349 * @extends CanvasShape
2351 CanvasPath = function(cfg)
2353 CanvasPath.superclass.constructor.apply(this, arguments);
2355 CanvasPath.NAME = "path";
2356 Y.extend(CanvasPath, Y.CanvasShape, {
2358 * Indicates the type of shape
2375 this._updateTransform();
2379 * Creates the dom node for the shape.
2381 * @method createNode
2382 * @return HTMLElement
2385 createNode: function()
2388 node = Y.config.doc.createElement('canvas'),
2390 concat = host._camelCaseConcat,
2391 id = host.get("id");
2392 host._context = node.getContext('2d');
2393 node.setAttribute("overflow", "visible");
2394 node.setAttribute("pointer-events", "none");
2395 node.style.pointerEvents = "none";
2396 node.style.overflow = "visible";
2397 node.setAttribute("id", id);
2400 host.addClass(_getClassName(SHAPE) + " " + _getClassName(concat(IMPLEMENTATION, SHAPE)) + " " + _getClassName(name) + " " + _getClassName(concat(IMPLEMENTATION, name)));
2404 * Completes a drawing operation.
2414 CanvasPath.ATTRS = Y.merge(Y.CanvasShape.ATTRS, {
2416 * Indicates the width of the shape
2424 var offset = this._stroke && this._strokeWeight ? (this._strokeWeight * 2) : 0;
2425 return this._width - offset;
2428 setter: function(val)
2436 * Indicates the height of the shape
2444 var offset = this._stroke && this._strokeWeight ? (this._strokeWeight * 2) : 0;
2445 return this._height - offset;
2448 setter: function(val)
2456 * Indicates the path used for the node.
2471 Y.CanvasPath = CanvasPath;
2473 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> implementation of the <a href="Rect.html">`Rect`</a> class.
2474 * `CanvasRect` is not intended to be used directly. Instead, use the <a href="Rect.html">`Rect`</a> class.
2475 * If the browser lacks <a href="http://www.w3.org/TR/SVG/">SVG</a> capabilities but has
2476 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> capabilities, the <a href="Rect.html">`Rect`</a>
2477 * class will point to the `CanvasRect` class.
2483 CanvasRect = function()
2485 CanvasRect.superclass.constructor.apply(this, arguments);
2487 CanvasRect.NAME = "rect";
2488 Y.extend(CanvasRect, Y.CanvasShape, {
2490 * Indicates the type of shape
2506 var w = this.get("width"),
2507 h = this.get("height");
2509 this.drawRect(0, 0, w, h);
2513 CanvasRect.ATTRS = Y.CanvasShape.ATTRS;
2514 Y.CanvasRect = CanvasRect;
2516 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> implementation of the <a href="Ellipse.html">`Ellipse`</a> class.
2517 * `CanvasEllipse` is not intended to be used directly. Instead, use the <a href="Ellipse.html">`Ellipse`</a> class.
2518 * If the browser lacks <a href="http://www.w3.org/TR/SVG/">SVG</a> capabilities but has
2519 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> capabilities, the <a href="Ellipse.html">`Ellipse`</a>
2520 * class will point to the `CanvasEllipse` class.
2523 * @class CanvasEllipse
2526 CanvasEllipse = function(cfg)
2528 CanvasEllipse.superclass.constructor.apply(this, arguments);
2531 CanvasEllipse.NAME = "ellipse";
2533 Y.extend(CanvasEllipse, CanvasShape, {
2535 * Indicates the type of shape
2551 var w = this.get("width"),
2552 h = this.get("height");
2554 this.drawEllipse(0, 0, w, h);
2558 CanvasEllipse.ATTRS = Y.merge(CanvasShape.ATTRS, {
2560 * Horizontal radius for the ellipse.
2566 setter: function(val)
2568 this.set("width", val * 2);
2573 var val = this.get("width");
2583 * Vertical radius for the ellipse.
2590 setter: function(val)
2592 this.set("height", val * 2);
2597 var val = this.get("height");
2606 Y.CanvasEllipse = CanvasEllipse;
2608 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> implementation of the <a href="Circle.html">`Circle`</a> class.
2609 * `CanvasCircle` is not intended to be used directly. Instead, use the <a href="Circle.html">`Circle`</a> class.
2610 * If the browser lacks <a href="http://www.w3.org/TR/SVG/">SVG</a> capabilities but has
2611 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> capabilities, the <a href="Circle.html">`Circle`</a>
2612 * class will point to the `CanvasCircle` class.
2615 * @class CanvasCircle
2618 CanvasCircle = function(cfg)
2620 CanvasCircle.superclass.constructor.apply(this, arguments);
2623 CanvasCircle.NAME = "circle";
2625 Y.extend(CanvasCircle, Y.CanvasShape, {
2627 * Indicates the type of shape
2643 var radius = this.get("radius");
2647 this.drawCircle(0, 0, radius);
2653 CanvasCircle.ATTRS = Y.merge(Y.CanvasShape.ATTRS, {
2655 * Indicates the width of the shape
2661 setter: function(val)
2663 this.set("radius", val/2);
2669 return this.get("radius") * 2;
2674 * Indicates the height of the shape
2680 setter: function(val)
2682 this.set("radius", val/2);
2688 return this.get("radius") * 2;
2693 * Radius of the circle
2702 Y.CanvasCircle = CanvasCircle;
2707 * @class CanvasPieSlice
2710 CanvasPieSlice = function()
2712 CanvasPieSlice.superclass.constructor.apply(this, arguments);
2714 CanvasPieSlice.NAME = "canvasPieSlice";
2715 Y.extend(CanvasPieSlice, Y.CanvasShape, {
2717 * Indicates the type of shape
2726 * Change event listener
2729 * @method _updateHandler
2733 var x = this.get("cx"),
2735 startAngle = this.get("startAngle"),
2736 arc = this.get("arc"),
2737 radius = this.get("radius");
2740 this._right = radius;
2742 this._bottom = radius;
2743 this.drawWedge(x, y, startAngle, arc, radius);
2747 CanvasPieSlice.ATTRS = Y.mix({
2756 * Starting angle in relation to a circle in which to begin the pie slice drawing.
2758 * @config startAngle
2776 * Radius of the circle in which the pie slice is drawn
2784 }, Y.CanvasShape.ATTRS);
2785 Y.CanvasPieSlice = CanvasPieSlice;
2787 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> implementation of the `Graphic` class.
2788 * `CanvasGraphic` is not intended to be used directly. Instead, use the <a href="Graphic.html">`Graphic`</a> class.
2789 * If the browser lacks <a href="http://www.w3.org/TR/SVG/">SVG</a> capabilities but has
2790 * <a href="http://www.w3.org/TR/html5/the-canvas-element.html">Canvas</a> capabilities, the <a href="Graphic.html">`Graphic`</a>
2791 * class will point to the `CanvasGraphic` class.
2794 * @class CanvasGraphic
2797 function CanvasGraphic(config) {
2799 CanvasGraphic.superclass.constructor.apply(this, arguments);
2802 CanvasGraphic.NAME = "canvasGraphic";
2804 CanvasGraphic.ATTRS = {
2806 * Whether or not to render the `Graphic` automatically after to a specified parent node after init. This can be a Node instance or a CSS selector string.
2809 * @type Node | String
2814 * Unique id for class instance.
2825 setter: function(val)
2827 var node = this._node;
2830 node.setAttribute("id", val);
2837 * Key value pairs in which a shape instance is associated with its id.
2848 return this._shapes;
2853 * Object containing size and coordinate data for the content of a Graphic in relation to the graphic instance's position.
2855 * @config contentBounds
2864 return this._contentBounds;
2869 * The outermost html element of the Graphic instance.
2885 * Indicates the width of the `Graphic`.
2891 setter: function(val)
2895 this._node.style.width = val + "px";
2902 * Indicates the height of the `Graphic`.
2908 setter: function(val)
2912 this._node.style.height = val + "px";
2919 * Determines the sizing of the Graphic.
2922 * <dt>sizeContentToGraphic</dt><dd>The Graphic's width and height attributes are, either explicitly set through the <code>width</code> and <code>height</code>
2923 * attributes or are determined by the dimensions of the parent element. The content contained in the Graphic will be sized to fit with in the Graphic instance's
2924 * dimensions. When using this setting, the <code>preserveAspectRatio</code> attribute will determine how the contents are sized.</dd>
2925 * <dt>sizeGraphicToContent</dt><dd>(Also accepts a value of true) The Graphic's width and height are determined by the size and positioning of the content.</dd>
2926 * <dt>false</dt><dd>The Graphic's width and height attributes are, either explicitly set through the <code>width</code> and <code>height</code>
2927 * attributes or are determined by the dimensions of the parent element. The contents of the Graphic instance are not affected by this setting.</dd>
2932 * @type Boolean | String
2940 * Determines how content is sized when <code>autoSize</code> is set to <code>sizeContentToGraphic</code>.
2943 * <dt>none<dt><dd>Do not force uniform scaling. Scale the graphic content of the given element non-uniformly if necessary
2944 * such that the element's bounding box exactly matches the viewport rectangle.</dd>
2945 * <dt>xMinYMin</dt><dd>Force uniform scaling position along the top left of the Graphic's node.</dd>
2946 * <dt>xMidYMin</dt><dd>Force uniform scaling horizontally centered and positioned at the top of the Graphic's node.<dd>
2947 * <dt>xMaxYMin</dt><dd>Force uniform scaling positioned horizontally from the right and vertically from the top.</dd>
2948 * <dt>xMinYMid</dt>Force uniform scaling positioned horizontally from the left and vertically centered.</dd>
2949 * <dt>xMidYMid (the default)</dt><dd>Force uniform scaling with the content centered.</dd>
2950 * <dt>xMaxYMid</dt><dd>Force uniform scaling positioned horizontally from the right and vertically centered.</dd>
2951 * <dt>xMinYMax</dt><dd>Force uniform scaling positioned horizontally from the left and vertically from the bottom.</dd>
2952 * <dt>xMidYMax</dt><dd>Force uniform scaling horizontally centered and position vertically from the bottom.</dd>
2953 * <dt>xMaxYMax</dt><dd>Force uniform scaling positioned horizontally from the right and vertically from the bottom.</dd>
2956 * @config preserveAspectRatio
2960 preserveAspectRatio: {
2965 * The contentBounds will resize to greater values but not smaller values. (for performance)
2966 * When resizing the contentBounds down is desirable, set the resizeDown value to true.
2968 * @config resizeDown
2976 * Indicates the x-coordinate for the instance.
2987 setter: function(val)
2992 this._node.style.left = val + "px";
2999 * Indicates the y-coordinate for the instance.
3010 setter: function(val)
3015 this._node.style.top = val + "px";
3022 * Indicates whether or not the instance will automatically redraw after a change is made to a shape.
3023 * This property will get set to false when batching operations.
3035 * Indicates whether the `Graphic` and its children are visible.
3043 setter: function(val)
3045 this._toggleVisible(val);
3051 Y.extend(CanvasGraphic, Y.GraphicBase, {
3053 * Sets the value of an attribute.
3056 * @param {String|Object} name The name of the attribute. Alternatively, an object of key value pairs can
3057 * be passed in to set multiple attributes at once.
3058 * @param {Any} value The value to set the attribute to. This value is ignored if an object is received as
3061 set: function(attr, value)
3067 preserveAspectRatio: true,
3071 forceRedraw = false;
3072 AttributeLite.prototype.set.apply(host, arguments);
3073 if(host._state.autoDraw === true && Y.Object.size(this._shapes) > 0)
3075 if(Y_LANG.isString && redrawAttrs[attr])
3079 else if(Y_LANG.isObject(attr))
3081 for(key in redrawAttrs)
3083 if(redrawAttrs.hasOwnProperty(key) && attr[key])
3098 * Storage for `x` attribute.
3107 * Storage for `y` attribute.
3116 * Gets the current position of the graphic instance in page coordinates.
3119 * @return Array The XY position of the shape.
3123 var node = Y.one(this._node),
3133 * Initializes the class.
3135 * @method initializer
3136 * @param {Object} config Optional attributes
3139 initializer: function(config) {
3140 var render = this.get("render"),
3141 visibility = this.get("visible") ? "visible" : "hidden",
3142 w = this.get("width") || 0,
3143 h = this.get("height") || 0;
3145 this._redrawQueue = {};
3146 this._contentBounds = {
3152 this._node = DOCUMENT.createElement('div');
3153 this._node.style.position = "absolute";
3154 this._node.style.visibility = visibility;
3155 this.set("width", w);
3156 this.set("height", h);
3159 this.render(render);
3164 * Adds the graphics node to the dom.
3167 * @param {HTMLElement} parentNode node in which to render the graphics node into.
3169 render: function(render) {
3170 var parentNode = Y.one(render),
3172 w = this.get("width") || parseInt(parentNode.getComputedStyle("width"), 10),
3173 h = this.get("height") || parseInt(parentNode.getComputedStyle("height"), 10);
3174 parentNode = parentNode || DOCUMENT.body;
3175 parentNode.appendChild(node);
3176 node.style.display = "block";
3177 node.style.position = "absolute";
3178 node.style.left = "0px";
3179 node.style.top = "0px";
3180 this.set("width", w);
3181 this.set("height", h);
3182 this.parentNode = parentNode;
3187 * Removes all nodes.
3193 this.removeAllShapes();
3196 this._removeChildren(this._node);
3197 Y.one(this._node).destroy();
3202 * Generates a shape instance by type.
3205 * @param {Object} cfg attributes for the shape
3208 addShape: function(cfg)
3211 if(!this.get("visible"))
3213 cfg.visible = false;
3215 var shapeClass = this._getShapeClass(cfg.type),
3216 shape = new shapeClass(cfg);
3217 this._appendShape(shape);
3222 * Adds a shape instance to the graphic instance.
3224 * @method _appendShape
3225 * @param {Shape} shape The shape instance to be added to the graphic.
3228 _appendShape: function(shape)
3230 var node = shape.node,
3231 parentNode = this._frag || this._node;
3232 if(this.get("autoDraw"))
3234 parentNode.appendChild(node);
3238 this._getDocFrag().appendChild(node);
3243 * Removes a shape instance from from the graphic instance.
3245 * @method removeShape
3246 * @param {Shape|String} shape The instance or id of the shape to be removed.
3248 removeShape: function(shape)
3250 if(!(shape instanceof CanvasShape))
3252 if(Y_LANG.isString(shape))
3254 shape = this._shapes[shape];
3257 if(shape && shape instanceof CanvasShape)
3260 delete this._shapes[shape.get("id")];
3262 if(this.get("autoDraw"))
3270 * Removes all shape instances from the dom.
3272 * @method removeAllShapes
3274 removeAllShapes: function()
3276 var shapes = this._shapes,
3280 if(shapes.hasOwnProperty(i))
3282 shapes[i].destroy();
3289 * Clears the graphics object.
3294 this.removeAllShapes();
3298 * Removes all child nodes.
3300 * @method _removeChildren
3301 * @param {HTMLElement} node
3304 _removeChildren: function(node)
3306 if(node && node.hasChildNodes())
3309 while(node.firstChild)
3311 child = node.firstChild;
3312 this._removeChildren(child);
3313 node.removeChild(child);
3319 * Toggles visibility
3321 * @method _toggleVisible
3322 * @param {Boolean} val indicates visibilitye
3325 _toggleVisible: function(val)
3328 shapes = this._shapes,
3329 visibility = val ? "visible" : "hidden";
3334 if(shapes.hasOwnProperty(i))
3336 shapes[i].set("visible", val);
3342 this._node.style.visibility = visibility;
3347 * Returns a shape class. Used by `addShape`.
3349 * @method _getShapeClass
3350 * @param {Shape | String} val Indicates which shape class.
3354 _getShapeClass: function(val)
3356 var shape = this._shapeClass[val];
3365 * Look up for shape classes. Used by `addShape` to retrieve a class for instantiation.
3367 * @property _shapeClass
3372 circle: Y.CanvasCircle,
3375 ellipse: Y.CanvasEllipse,
3376 pieslice: Y.CanvasPieSlice
3380 * Returns a shape based on the id of its dom node.
3382 * @method getShapeById
3383 * @param {String} id Dom id of the shape's node attribute.
3386 getShapeById: function(id)
3388 var shape = this._shapes[id];
3393 * Allows for creating multiple shapes in order to batch appending and redraw operations.
3396 * @param {Function} method Method to execute.
3398 batch: function(method)
3400 var autoDraw = this.get("autoDraw");
3401 this.set("autoDraw", false);
3403 this.set("autoDraw", autoDraw);
3407 * Returns a document fragment to for attaching shapes.
3409 * @method _getDocFrag
3410 * @return DocumentFragment
3413 _getDocFrag: function()
3417 this._frag = DOCUMENT.createDocumentFragment();
3423 * Redraws all shapes.
3430 var autoSize = this.get("autoSize"),
3431 preserveAspectRatio = this.get("preserveAspectRatio"),
3432 box = this.get("resizeDown") ? this._getUpdatedContentBounds() : this._contentBounds,
3442 node = this.get("node");
3445 if(autoSize == "sizeContentToGraphic")
3447 contentWidth = box.right - box.left;
3448 contentHeight = box.bottom - box.top;
3449 w = parseFloat(Y_DOM.getComputedStyle(node, "width"));
3450 h = parseFloat(Y_DOM.getComputedStyle(node, "height"));
3451 matrix = new Y.Matrix();
3452 if(preserveAspectRatio == "none")
3454 xScale = w/contentWidth;
3455 yScale = h/contentHeight;
3459 if(contentWidth/contentHeight !== w/h)
3461 if(contentWidth * h/contentHeight > w)
3463 xScale = yScale = w/contentWidth;
3464 translateY = this._calculateTranslate(preserveAspectRatio.slice(5).toLowerCase(), contentHeight * w/contentWidth, h);
3468 xScale = yScale = h/contentHeight;
3469 translateX = this._calculateTranslate(preserveAspectRatio.slice(1, 4).toLowerCase(), contentWidth * h/contentHeight, w);
3473 Y_DOM.setStyle(node, "transformOrigin", "0% 0%");
3474 translateX = translateX - (box.left * xScale);
3475 translateY = translateY - (box.top * yScale);
3476 matrix.translate(translateX, translateY);
3477 matrix.scale(xScale, yScale);
3478 Y_DOM.setStyle(node, "transform", matrix.toCSSText());
3482 this.set("width", box.right);
3483 this.set("height", box.bottom);
3488 this._node.appendChild(this._frag);
3494 * Determines the value for either an x or y value to be used for the <code>translate</code> of the Graphic.
3496 * @method _calculateTranslate
3497 * @param {String} position The position for placement. Possible values are min, mid and max.
3498 * @param {Number} contentSize The total size of the content.
3499 * @param {Number} boundsSize The total size of the Graphic.
3503 _calculateTranslate: function(position, contentSize, boundsSize)
3505 var ratio = boundsSize - contentSize,
3510 coord = ratio * 0.5;
3523 * Adds a shape to the redraw queue and calculates the contentBounds. Used internally
3524 * by `Shape` instances.
3526 * @method addToRedrawQueue
3527 * @param Shape shape The shape instance to add to the queue
3530 addToRedrawQueue: function(shape)
3534 this._shapes[shape.get("id")] = shape;
3535 if(!this.get("resizeDown"))
3537 shapeBox = shape.getBounds();
3538 box = this._contentBounds;
3539 box.left = box.left < shapeBox.left ? box.left : shapeBox.left;
3540 box.top = box.top < shapeBox.top ? box.top : shapeBox.top;
3541 box.right = box.right > shapeBox.right ? box.right : shapeBox.right;
3542 box.bottom = box.bottom > shapeBox.bottom ? box.bottom : shapeBox.bottom;
3543 this._contentBounds = box;
3545 if(this.get("autoDraw"))
3552 * Recalculates and returns the `contentBounds` for the `Graphic` instance.
3554 * @method _getUpdatedContentBounds
3558 _getUpdatedContentBounds: function()
3563 queue = this._shapes,
3567 if(queue.hasOwnProperty(i))
3570 bounds = shape.getBounds();
3571 box.left = Y_LANG.isNumber(box.left) ? Math.min(box.left, bounds.left) : bounds.left;
3572 box.top = Y_LANG.isNumber(box.top) ? Math.min(box.top, bounds.top) : bounds.top;
3573 box.right = Y_LANG.isNumber(box.right) ? Math.max(box.right, bounds.right) : bounds.right;
3574 box.bottom = Y_LANG.isNumber(box.bottom) ? Math.max(box.bottom, bounds.bottom) : bounds.bottom;
3577 box.left = Y_LANG.isNumber(box.left) ? box.left : 0;
3578 box.top = Y_LANG.isNumber(box.top) ? box.top : 0;
3579 box.right = Y_LANG.isNumber(box.right) ? box.right : 0;
3580 box.bottom = Y_LANG.isNumber(box.bottom) ? box.bottom : 0;
3581 this._contentBounds = box;
3586 * Inserts shape on the top of the tree.
3589 * @param {CanvasShape} Shape to add.
3592 _toFront: function(shape)
3594 var contentNode = this.get("node");
3595 if(shape instanceof Y.CanvasShape)
3597 shape = shape.get("node");
3599 if(contentNode && shape)
3601 contentNode.appendChild(shape);
3606 * Inserts shape as the first child of the content node.
3609 * @param {CanvasShape} Shape to add.
3612 _toBack: function(shape)
3614 var contentNode = this.get("node"),
3616 if(shape instanceof Y.CanvasShape)
3618 shape = shape.get("node");
3620 if(contentNode && shape)
3622 targetNode = contentNode.firstChild;
3625 contentNode.insertBefore(shape, targetNode);
3629 contentNode.appendChild(shape);
3635 Y.CanvasGraphic = CanvasGraphic;
3638 }, '3.7.2', {"requires": ["graphics"]});