Advertisement
Guest User

Excanvas_MOD

a guest
May 16th, 2011
803
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Copyright 2006 Google Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. //   http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14.  
  15.  
  16. // Known Issues:
  17. //
  18. // * Patterns are not implemented.
  19. // * Radial gradient are not implemented. The VML version of these look very
  20. //   different from the canvas one.
  21. // * Clipping paths are not implemented.
  22. // * Coordsize. The width and height attribute have higher priority than the
  23. //   width and height style values which isn't correct.
  24. // * Painting mode isn't implemented.
  25. // * Canvas width/height should is using content-box by default. IE in
  26. //   Quirks mode will draw the canvas using border-box. Either change your
  27. //   doctype to HTML5
  28. //   (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype)
  29. //   or use Box Sizing Behavior from WebFX
  30. //   (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html)
  31. // * Non uniform scaling does not correctly scale strokes.
  32. // * Optimize. There is always room for speed improvements.
  33.  
  34. // Only add this code if we do not already have a canvas implementation
  35. if (!document.createElement('canvas').getContext) {
  36.  
  37. var counter =0;
  38.    
  39. (function() {
  40.  
  41.   // alias some functions to make (compiled) code shorter
  42.   var m = Math;
  43.   var mr = m.round;
  44.   var ms = m.sin;
  45.   var mc = m.cos;
  46.   var abs = m.abs;
  47.   var sqrt = m.sqrt;
  48.  
  49.   // this is used for sub pixel precision
  50.   var Z = 10;
  51.   var Z2 = Z / 2;
  52.  
  53.   /**
  54.    * This funtion is assigned to the <canvas> elements as element.getContext().
  55.    * @this {HTMLElement}
  56.    * @return {CanvasRenderingContext2D_}
  57.    */
  58.   function getContext() {
  59.     return this.context_ ||
  60.         (this.context_ = new CanvasRenderingContext2D_(this));
  61.   }
  62.  
  63.   var slice = Array.prototype.slice;
  64.  
  65.   /**
  66.    * Binds a function to an object. The returned function will always use the
  67.    * passed in {@code obj} as {@code this}.
  68.    *
  69.    * Example:
  70.    *
  71.    *   g = bind(f, obj, a, b)
  72.    *   g(c, d) // will do f.call(obj, a, b, c, d)
  73.    *
  74.    * @param {Function} f The function to bind the object to
  75.    * @param {Object} obj The object that should act as this when the function
  76.    *     is called
  77.    * @param {*} var_args Rest arguments that will be used as the initial
  78.    *     arguments when the function is called
  79.    * @return {Function} A new function that has bound this
  80.    */
  81.   function bind(f, obj, var_args) {
  82.     var a = slice.call(arguments, 2);
  83.     return function() {
  84.       return f.apply(obj, a.concat(slice.call(arguments)));
  85.     };
  86.   }
  87.  
  88.   var G_vmlCanvasManager_ = {
  89.     init: function(opt_doc) {
  90.       if (/MSIE/.test(navigator.userAgent) && !window.opera) {
  91.         var doc = opt_doc || document;
  92.         // Create a dummy element so that IE will allow canvas elements to be
  93.         // recognized.
  94.         doc.createElement('canvas');
  95.         doc.attachEvent('onreadystatechange', bind(this.init_, this, doc));
  96.       }
  97.     },
  98.  
  99.     init_: function(doc) {
  100.       // create xmlns
  101.       if (!doc.namespaces['g_vml_']) {
  102.         doc.namespaces.add('g_vml_', 'urn:schemas-microsoft-com:vml',
  103.                            '#default#VML');
  104.  
  105.       }
  106.       if (!doc.namespaces['g_o_']) {
  107.         doc.namespaces.add('g_o_', 'urn:schemas-microsoft-com:office:office',
  108.                            '#default#VML');
  109.       }
  110.  
  111.       // Setup default CSS.  Only add one style sheet per document
  112.       if (!doc.styleSheets['ex_canvas_']) {
  113.         var ss = doc.createStyleSheet();
  114.         ss.owningElement.id = 'ex_canvas_';
  115.         ss.cssText = 'canvas{display:inline-block;overflow:hidden;' +
  116.             // default size is 300x150 in Gecko and Opera
  117.             'text-align:left;width:300px;height:150px}' +
  118.             'g_vml_\\:*{behavior:url(#default#VML)}' +
  119.             'g_o_\\:*{behavior:url(#default#VML)}';
  120.  
  121.       }
  122.  
  123.       // find all canvas elements
  124.       var els = doc.getElementsByTagName('canvas');
  125.       for (var i = 0; i < els.length; i++) {
  126.         this.initElement(els[i]);
  127.       }
  128.     },
  129.  
  130.     /**
  131.      * Public initializes a canvas element so that it can be used as canvas
  132.      * element from now on. This is called automatically before the page is
  133.      * loaded but if you are creating elements using createElement you need to
  134.      * make sure this is called on the element.
  135.      * @param {HTMLElement} el The canvas element to initialize.
  136.      * @return {HTMLElement} the element that was created.
  137.      */
  138.     initElement: function(el) {
  139.       if (!el.getContext) {
  140.  
  141.         el.getContext = getContext;
  142.  
  143.         // Remove fallback content. There is no way to hide text nodes so we
  144.         // just remove all childNodes. We could hide all elements and remove
  145.         // text nodes but who really cares about the fallback content.
  146.         el.innerHTML = '';
  147.  
  148.         // do not use inline function because that will leak memory
  149.         el.attachEvent('onpropertychange', onPropertyChange);
  150.         el.attachEvent('onresize', onResize);
  151.  
  152.         var attrs = el.attributes;
  153.         if (attrs.width && attrs.width.specified) {
  154.           // TODO: use runtimeStyle and coordsize
  155.           // el.getContext().setWidth_(attrs.width.nodeValue);
  156.           el.style.width = attrs.width.nodeValue + 'px';
  157.         } else {
  158.           el.width = el.clientWidth;
  159.         }
  160.         if (attrs.height && attrs.height.specified) {
  161.           // TODO: use runtimeStyle and coordsize
  162.           // el.getContext().setHeight_(attrs.height.nodeValue);
  163.           el.style.height = attrs.height.nodeValue + 'px';
  164.         } else {
  165.           el.height = el.clientHeight;
  166.         }
  167.         //el.getContext().setCoordsize_()
  168.       }
  169.       return el;
  170.     }
  171.   };
  172.  
  173.   function onPropertyChange(e) {
  174.     var el = e.srcElement;
  175.  
  176.     switch (e.propertyName) {
  177.       case 'width':
  178.         el.style.width = el.attributes.width.nodeValue + 'px';
  179.         el.getContext().clearRect();
  180.         break;
  181.       case 'height':
  182.         el.style.height = el.attributes.height.nodeValue + 'px';
  183.         el.getContext().clearRect();
  184.         break;
  185.     }
  186.   }
  187.  
  188.   function onResize(e) {
  189.     var el = e.srcElement;
  190.     if (el.firstChild) {
  191.       el.firstChild.style.width =  el.clientWidth + 'px';
  192.       el.firstChild.style.height = el.clientHeight + 'px';
  193.     }
  194.   }
  195.  
  196.   G_vmlCanvasManager_.init();
  197.  
  198.   // precompute "00" to "FF"
  199.   var dec2hex = [];
  200.   for (var i = 0; i < 16; i++) {
  201.     for (var j = 0; j < 16; j++) {
  202.       dec2hex[i * 16 + j] = i.toString(16) + j.toString(16);
  203.     }
  204.   }
  205.  
  206.   function createMatrixIdentity() {
  207.     return [
  208.       [1, 0, 0],
  209.       [0, 1, 0],
  210.       [0, 0, 1]
  211.     ];
  212.   }
  213.  
  214.   function matrixMultiply(m1, m2) {
  215.     var result = createMatrixIdentity();
  216.  
  217.     for (var x = 0; x < 3; x++) {
  218.       for (var y = 0; y < 3; y++) {
  219.         var sum = 0;
  220.  
  221.         for (var z = 0; z < 3; z++) {
  222.           sum += m1[x][z] * m2[z][y];
  223.         }
  224.  
  225.         result[x][y] = sum;
  226.       }
  227.     }
  228.     return result;
  229.   }
  230.  
  231.   function copyState(o1, o2) {
  232.     o2.fillStyle     = o1.fillStyle;
  233.     o2.lineCap       = o1.lineCap;
  234.     o2.lineJoin      = o1.lineJoin;
  235.     o2.lineWidth     = o1.lineWidth;
  236.     o2.miterLimit    = o1.miterLimit;
  237.     o2.shadowBlur    = o1.shadowBlur;
  238.     o2.shadowColor   = o1.shadowColor;
  239.     o2.shadowOffsetX = o1.shadowOffsetX;
  240.     o2.shadowOffsetY = o1.shadowOffsetY;
  241.     o2.strokeStyle   = o1.strokeStyle;
  242.     o2.globalAlpha   = o1.globalAlpha;
  243.     o2.arcScaleX_    = o1.arcScaleX_;
  244.     o2.arcScaleY_    = o1.arcScaleY_;
  245.     o2.lineScale_    = o1.lineScale_;
  246.   }
  247.  
  248.   function processStyle(styleString) {
  249.     var str, alpha = 1;
  250.  
  251.     styleString = String(styleString);
  252.     if (styleString.substring(0, 3) == 'rgb') {
  253.       var start = styleString.indexOf('(', 3);
  254.       var end = styleString.indexOf(')', start + 1);
  255.       var guts = styleString.substring(start + 1, end).split(',');
  256.  
  257.       str = '#';
  258.       for (var i = 0; i < 3; i++) {
  259.         str += dec2hex[Number(guts[i])];
  260.       }
  261.  
  262.       if (guts.length == 4 && styleString.substr(3, 1) == 'a') {
  263.         alpha = guts[3];
  264.       }
  265.     } else {
  266.       str = styleString;
  267.     }
  268.  
  269.     return {color: str, alpha: alpha};
  270.   }
  271.  
  272.   function processLineCap(lineCap) {
  273.     switch (lineCap) {
  274.       case 'butt':
  275.         return 'flat';
  276.       case 'round':
  277.         return 'round';
  278.       case 'square':
  279.       default:
  280.         return 'square';
  281.     }
  282.   }
  283.  
  284.   /**
  285.    * This class implements CanvasRenderingContext2D interface as described by
  286.    * the WHATWG.
  287.    * @param {HTMLElement} surfaceElement The element that the 2D context should
  288.    * be associated with
  289.    */
  290.   function CanvasRenderingContext2D_(surfaceElement) {
  291.     this.m_ = createMatrixIdentity();
  292.  
  293.     this.mStack_ = [];
  294.     this.aStack_ = [];
  295.     this.currentPath_ = [];
  296.  
  297.     // Canvas context properties
  298.     this.strokeStyle = '#000';
  299.     this.fillStyle = '#000';
  300.  
  301.     this.lineWidth = 1;
  302.     this.lineJoin = 'miter';
  303.     this.lineCap = 'butt';
  304.     this.miterLimit = Z * 1;
  305.     this.globalAlpha = 1;
  306.     this.canvas = surfaceElement;
  307.  
  308.     var el = surfaceElement.ownerDocument.createElement('div');
  309.     el.className = "seriesContainer_"+counter;
  310.     el.style.width =  surfaceElement.clientWidth + 'px';
  311.     el.style.height = surfaceElement.clientHeight + 'px';
  312.     el.style.overflow = 'hidden';
  313.     el.style.position = 'absolute';
  314.     surfaceElement.appendChild(el);
  315.  
  316.     this.element_ = el;
  317.     this.arcScaleX_ = 1;
  318.     this.arcScaleY_ = 1;
  319.     this.lineScale_ = 1;
  320.     counter++;
  321.   }
  322.  
  323.   var contextPrototype = CanvasRenderingContext2D_.prototype;
  324.   contextPrototype.clearRect = function() {
  325.     this.element_.innerHTML = '';
  326.   };
  327.  
  328.   contextPrototype.beginPath = function() {
  329.     // TODO: Branch current matrix so that save/restore has no effect
  330.     //       as per safari docs.
  331.     this.currentPath_ = [];
  332.   };
  333.  
  334.   contextPrototype.moveTo = function(aX, aY) {
  335.     var p = this.getCoords_(aX, aY);
  336.     this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y});
  337.     this.currentX_ = p.x;
  338.     this.currentY_ = p.y;
  339.   };
  340.  
  341.   contextPrototype.lineTo = function(aX, aY) {
  342.     var p = this.getCoords_(aX, aY);
  343.     this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y});
  344.  
  345.     this.currentX_ = p.x;
  346.     this.currentY_ = p.y;
  347.   };
  348.  
  349.   contextPrototype.bezierCurveTo = function(aCP1x, aCP1y,
  350.                                             aCP2x, aCP2y,
  351.                                             aX, aY) {
  352.     var p = this.getCoords_(aX, aY);
  353.     var cp1 = this.getCoords_(aCP1x, aCP1y);
  354.     var cp2 = this.getCoords_(aCP2x, aCP2y);
  355.     bezierCurveTo(this, cp1, cp2, p);
  356.   };
  357.  
  358.   // Helper function that takes the already fixed cordinates.
  359.   function bezierCurveTo(self, cp1, cp2, p) {
  360.     self.currentPath_.push({
  361.       type: 'bezierCurveTo',
  362.       cp1x: cp1.x,
  363.       cp1y: cp1.y,
  364.       cp2x: cp2.x,
  365.       cp2y: cp2.y,
  366.       x: p.x,
  367.       y: p.y
  368.     });
  369.     self.currentX_ = p.x;
  370.     self.currentY_ = p.y;
  371.   }
  372.  
  373.   contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) {
  374.     // the following is lifted almost directly from
  375.     // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes
  376.  
  377.     var cp = this.getCoords_(aCPx, aCPy);
  378.     var p = this.getCoords_(aX, aY);
  379.  
  380.     var cp1 = {
  381.       x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_),
  382.       y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_)
  383.     };
  384.     var cp2 = {
  385.       x: cp1.x + (p.x - this.currentX_) / 3.0,
  386.       y: cp1.y + (p.y - this.currentY_) / 3.0
  387.     };
  388.  
  389.     bezierCurveTo(this, cp1, cp2, p);
  390.   };
  391.  
  392.   contextPrototype.arc = function(aX, aY, aRadius,
  393.                                   aStartAngle, aEndAngle, aClockwise) {
  394.     aRadius *= Z;
  395.     var arcType = aClockwise ? 'at' : 'wa';
  396.  
  397.     var xStart = aX + mc(aStartAngle) * aRadius - Z2;
  398.     var yStart = aY + ms(aStartAngle) * aRadius - Z2;
  399.  
  400.     var xEnd = aX + mc(aEndAngle) * aRadius - Z2;
  401.     var yEnd = aY + ms(aEndAngle) * aRadius - Z2;
  402.  
  403.     // IE won't render arches drawn counter clockwise if xStart == xEnd.
  404.     if (xStart == xEnd && !aClockwise) {
  405.       xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something
  406.                        // that can be represented in binary
  407.     }
  408.  
  409.     var p = this.getCoords_(aX, aY);
  410.     var pStart = this.getCoords_(xStart, yStart);
  411.     var pEnd = this.getCoords_(xEnd, yEnd);
  412.  
  413.     this.currentPath_.push({type: arcType,
  414.                            x: p.x,
  415.                            y: p.y,
  416.                            radius: aRadius,
  417.                            xStart: pStart.x,
  418.                            yStart: pStart.y,
  419.                            xEnd: pEnd.x,
  420.                            yEnd: pEnd.y});
  421.  
  422.   };
  423.  
  424.   contextPrototype.rect = function(aX, aY, aWidth, aHeight) {
  425.     this.moveTo(aX, aY);
  426.     this.lineTo(aX + aWidth, aY);
  427.     this.lineTo(aX + aWidth, aY + aHeight);
  428.     this.lineTo(aX, aY + aHeight);
  429.     this.closePath();
  430.   };
  431.  
  432.   contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) {
  433.     var oldPath = this.currentPath_;
  434.     this.beginPath();
  435.  
  436.     this.moveTo(aX, aY);
  437.     this.lineTo(aX + aWidth, aY);
  438.     this.lineTo(aX + aWidth, aY + aHeight);
  439.     this.lineTo(aX, aY + aHeight);
  440.     this.closePath();
  441.     this.stroke();
  442.  
  443.     this.currentPath_ = oldPath;
  444.   };
  445.  
  446.   contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) {
  447.     var oldPath = this.currentPath_;
  448.     this.beginPath();
  449.  
  450.     this.moveTo(aX, aY);
  451.     this.lineTo(aX + aWidth, aY);
  452.     this.lineTo(aX + aWidth, aY + aHeight);
  453.     this.lineTo(aX, aY + aHeight);
  454.     this.closePath();
  455.     this.fill();
  456.  
  457.     this.currentPath_ = oldPath;
  458.   };
  459.  
  460.   contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) {
  461.     var gradient = new CanvasGradient_('gradient');
  462.     gradient.x0_ = aX0;
  463.     gradient.y0_ = aY0;
  464.     gradient.x1_ = aX1;
  465.     gradient.y1_ = aY1;
  466.     return gradient;
  467.   };
  468.  
  469.   contextPrototype.createRadialGradient = function(aX0, aY0, aR0,
  470.                                                    aX1, aY1, aR1) {
  471.     var gradient = new CanvasGradient_('gradientradial');
  472.     gradient.x0_ = aX0;
  473.     gradient.y0_ = aY0;
  474.     gradient.r0_ = aR0;
  475.     gradient.x1_ = aX1;
  476.     gradient.y1_ = aY1;
  477.     gradient.r1_ = aR1;
  478.     return gradient;
  479.   };
  480.  
  481.   contextPrototype.drawImage = function(image, var_args) {
  482.     var dx, dy, dw, dh, sx, sy, sw, sh;
  483.  
  484.     // to find the original width we overide the width and height
  485.     var oldRuntimeWidth = image.runtimeStyle.width;
  486.     var oldRuntimeHeight = image.runtimeStyle.height;
  487.     image.runtimeStyle.width = 'auto';
  488.     image.runtimeStyle.height = 'auto';
  489.  
  490.     // get the original size
  491.     var w = image.width;
  492.     var h = image.height;
  493.  
  494.     // and remove overides
  495.     image.runtimeStyle.width = oldRuntimeWidth;
  496.     image.runtimeStyle.height = oldRuntimeHeight;
  497.  
  498.     if (arguments.length == 3) {
  499.       dx = arguments[1];
  500.       dy = arguments[2];
  501.       sx = sy = 0;
  502.       sw = dw = w;
  503.       sh = dh = h;
  504.     } else if (arguments.length == 5) {
  505.       dx = arguments[1];
  506.       dy = arguments[2];
  507.       dw = arguments[3];
  508.       dh = arguments[4];
  509.       sx = sy = 0;
  510.       sw = w;
  511.       sh = h;
  512.     } else if (arguments.length == 9) {
  513.       sx = arguments[1];
  514.       sy = arguments[2];
  515.       sw = arguments[3];
  516.       sh = arguments[4];
  517.       dx = arguments[5];
  518.       dy = arguments[6];
  519.       dw = arguments[7];
  520.       dh = arguments[8];
  521.     } else {
  522.       throw Error('Invalid number of arguments');
  523.     }
  524.  
  525.     var d = this.getCoords_(dx, dy);
  526.  
  527.     var w2 = sw / 2;
  528.     var h2 = sh / 2;
  529.  
  530.     var vmlStr = [];
  531.  
  532.     var W = 10;
  533.     var H = 10;
  534.  
  535.     // For some reason that I've now forgotten, using divs didn't work
  536.     vmlStr.push(' <g_vml_:group',
  537.                 ' coordsize="', Z * W, ',', Z * H, '"',
  538.                 ' coordorigin="0,0"' ,
  539.                 ' style="width:', W, 'px;height:', H, 'px;position:absolute;');
  540.  
  541.     // If filters are necessary (rotation exists), create them
  542.     // filters are bog-slow, so only create them if abbsolutely necessary
  543.     // The following check doesn't account for skews (which don't exist
  544.     // in the canvas spec (yet) anyway.
  545.  
  546.     if (this.m_[0][0] != 1 || this.m_[0][1]) {
  547.       var filter = [];
  548.  
  549.       // Note the 12/21 reversal
  550.       filter.push('M11=', this.m_[0][0], ',',
  551.                   'M12=', this.m_[1][0], ',',
  552.                   'M21=', this.m_[0][1], ',',
  553.                   'M22=', this.m_[1][1], ',',
  554.                   'Dx=', mr(d.x / Z), ',',
  555.                   'Dy=', mr(d.y / Z), '');
  556.  
  557.       // Bounding box calculation (need to minimize displayed area so that
  558.       // filters don't waste time on unused pixels.
  559.       var max = d;
  560.       var c2 = this.getCoords_(dx + dw, dy);
  561.       var c3 = this.getCoords_(dx, dy + dh);
  562.       var c4 = this.getCoords_(dx + dw, dy + dh);
  563.  
  564.       max.x = m.max(max.x, c2.x, c3.x, c4.x);
  565.       max.y = m.max(max.y, c2.y, c3.y, c4.y);
  566.  
  567.       vmlStr.push('padding:0 ', mr(max.x / Z), 'px ', mr(max.y / Z),
  568.                   'px 0;filter:progid:DXImageTransform.Microsoft.Matrix(',
  569.                   filter.join(''), ", sizingmethod='clip');")
  570.     } else {
  571.       vmlStr.push('top:', mr(d.y / Z), 'px;left:', mr(d.x / Z), 'px;');
  572.     }
  573.  
  574.     vmlStr.push(' ">' ,
  575.                 '<g_vml_:image src="', image.src, '"',
  576.                 ' style="width:', Z * dw, 'px;',
  577.                 ' height:', Z * dh, 'px;"',
  578.                 ' cropleft="', sx / w, '"',
  579.                 ' croptop="', sy / h, '"',
  580.                 ' cropright="', (w - sx - sw) / w, '"',
  581.                 ' cropbottom="', (h - sy - sh) / h, '"',
  582.                 ' />',
  583.                 '</g_vml_:group>');
  584.  
  585.     this.element_.insertAdjacentHTML('BeforeEnd',
  586.                                     vmlStr.join(''));
  587.   };
  588.  
  589.   contextPrototype.stroke = function(aFill) {
  590.     var lineStr = [];
  591.     var lineOpen = false;
  592.     var a = processStyle(aFill ? this.fillStyle : this.strokeStyle);
  593.     var color = a.color;
  594.     var opacity = a.alpha * this.globalAlpha;
  595.  
  596.     var W = 10;
  597.     var H = 10;
  598.  
  599.     lineStr.push('<g_vml_:shape',
  600.                  ' filled="', !!aFill, '"',
  601.                  ' style="position:absolute;width:', W, 'px;height:', H, 'px;"',
  602.                  ' coordorigin="0 0" coordsize="', Z * W, ' ', Z * H, '"',
  603.                  ' stroked="', !aFill, '"',
  604.                  ' path="');
  605.  
  606.     var newSeq = false;
  607.     var min = {x: null, y: null};
  608.     var max = {x: null, y: null};
  609.  
  610.     for (var i = 0; i < this.currentPath_.length; i++) {
  611.       var p = this.currentPath_[i];
  612.       var c;
  613.  
  614.       switch (p.type) {
  615.         case 'moveTo':
  616.           c = p;
  617.           lineStr.push(' m ', mr(p.x), ',', mr(p.y));
  618.           break;
  619.         case 'lineTo':
  620.           lineStr.push(' l ', mr(p.x), ',', mr(p.y));
  621.           break;
  622.         case 'close':
  623.           lineStr.push(' x ');
  624.           p = null;
  625.           break;
  626.         case 'bezierCurveTo':
  627.           lineStr.push(' c ',
  628.                        mr(p.cp1x), ',', mr(p.cp1y), ',',
  629.                        mr(p.cp2x), ',', mr(p.cp2y), ',',
  630.                        mr(p.x), ',', mr(p.y));
  631.           break;
  632.         case 'at':
  633.         case 'wa':
  634.           lineStr.push(' ', p.type, ' ',
  635.                        mr(p.x - this.arcScaleX_ * p.radius), ',',
  636.                        mr(p.y - this.arcScaleY_ * p.radius), ' ',
  637.                        mr(p.x + this.arcScaleX_ * p.radius), ',',
  638.                        mr(p.y + this.arcScaleY_ * p.radius), ' ',
  639.                        mr(p.xStart), ',', mr(p.yStart), ' ',
  640.                        mr(p.xEnd), ',', mr(p.yEnd));
  641.           break;
  642.       }
  643.  
  644.  
  645.       // TODO: Following is broken for curves due to
  646.       //       move to proper paths.
  647.  
  648.       // Figure out dimensions so we can do gradient fills
  649.       // properly
  650.       if (p) {
  651.         if (min.x == null || p.x < min.x) {
  652.           min.x = p.x;
  653.         }
  654.         if (max.x == null || p.x > max.x) {
  655.           max.x = p.x;
  656.         }
  657.         if (min.y == null || p.y < min.y) {
  658.           min.y = p.y;
  659.         }
  660.         if (max.y == null || p.y > max.y) {
  661.           max.y = p.y;
  662.         }
  663.       }
  664.     }
  665.     lineStr.push(' ">');
  666.  
  667.     if (!aFill) {
  668.       var lineWidth = this.lineScale_ * this.lineWidth;
  669.  
  670.       // VML cannot correctly render a line if the width is less than 1px.
  671.       // In that case, we dilute the color to make the line look thinner.
  672.       if (lineWidth < 1) {
  673.         opacity *= lineWidth;
  674.       }
  675.  
  676.       lineStr.push(
  677.         '<g_vml_:stroke',
  678.         ' opacity="', opacity, '"',
  679.         ' joinstyle="', this.lineJoin, '"',
  680.         ' miterlimit="', this.miterLimit, '"',
  681.         ' endcap="', processLineCap(this.lineCap), '"',
  682.         ' weight="', lineWidth, 'px"',
  683.         ' color="', color, '" />'
  684.       );
  685.     } else if (typeof this.fillStyle == 'object') {
  686.       var fillStyle = this.fillStyle;
  687.       var angle = 0;
  688.       var focus = {x: 0, y: 0};
  689.  
  690.       // additional offset
  691.       var shift = 0;
  692.       // scale factor for offset
  693.       var expansion = 1;
  694.  
  695.       if (fillStyle.type_ == 'gradient') {
  696.         var x0 = fillStyle.x0_ / this.arcScaleX_;
  697.         var y0 = fillStyle.y0_ / this.arcScaleY_;
  698.         var x1 = fillStyle.x1_ / this.arcScaleX_;
  699.         var y1 = fillStyle.y1_ / this.arcScaleY_;
  700.         var p0 = this.getCoords_(x0, y0);
  701.         var p1 = this.getCoords_(x1, y1);
  702.         var dx = p1.x - p0.x;
  703.         var dy = p1.y - p0.y;
  704.         angle = Math.atan2(dx, dy) * 180 / Math.PI;
  705.  
  706.         // The angle should be a non-negative number.
  707.         if (angle < 0) {
  708.           angle += 360;
  709.         }
  710.  
  711.         // Very small angles produce an unexpected result because they are
  712.         // converted to a scientific notation string.
  713.         if (angle < 1e-6) {
  714.           angle = 0;
  715.         }
  716.       } else {
  717.         var p0 = this.getCoords_(fillStyle.x0_, fillStyle.y0_);
  718.         var width  = max.x - min.x;
  719.         var height = max.y - min.y;
  720.         focus = {
  721.           x: (p0.x - min.x) / width,
  722.           y: (p0.y - min.y) / height
  723.         };
  724.  
  725.         width  /= this.arcScaleX_ * Z;
  726.         height /= this.arcScaleY_ * Z;
  727.         var dimension = m.max(width, height);
  728.         shift = 2 * fillStyle.r0_ / dimension;
  729.         expansion = 2 * fillStyle.r1_ / dimension - shift;
  730.       }
  731.  
  732.       // We need to sort the color stops in ascending order by offset,
  733.       // otherwise IE won't interpret it correctly.
  734.       var stops = fillStyle.colors_;
  735.       stops.sort(function(cs1, cs2) {
  736.         return cs1.offset - cs2.offset;
  737.       });
  738.  
  739.       var length = stops.length;
  740.       var color1 = stops[0].color;
  741.       var color2 = stops[length - 1].color;
  742.       var opacity1 = stops[0].alpha * this.globalAlpha;
  743.       var opacity2 = stops[length - 1].alpha * this.globalAlpha;
  744.  
  745.       var colors = [];
  746.       for (var i = 0; i < length; i++) {
  747.         var stop = stops[i];
  748.         colors.push(stop.offset * expansion + shift + ' ' + stop.color);
  749.       }
  750.  
  751.       // When colors attribute is used, the meanings of opacity and o:opacity2
  752.       // are reversed.
  753.       lineStr.push('<g_vml_:fill type="', fillStyle.type_, '"',
  754.                    ' method="none" focus="100%"',
  755.                    ' color="', color1, '"',
  756.                    ' color2="', color2, '"',
  757.                    ' colors="', colors.join(','), '"',
  758.                    ' opacity="', opacity2, '"',
  759.                    ' g_o_:opacity2="', opacity1, '"',
  760.                    ' angle="', angle, '"',
  761.                    ' focusposition="', focus.x, ',', focus.y, '" />');
  762.     } else {
  763.       lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity,
  764.                    '" />');
  765.     }
  766.  
  767.     lineStr.push('</g_vml_:shape>');
  768.  
  769.     this.element_.insertAdjacentHTML('beforeEnd', lineStr.join(''));
  770.   };
  771.  
  772.   contextPrototype.fill = function() {
  773.     this.stroke(true);
  774.   }
  775.  
  776.   contextPrototype.closePath = function() {
  777.     this.currentPath_.push({type: 'close'});
  778.   };
  779.  
  780.   /**
  781.    * @private
  782.    */
  783.   contextPrototype.getCoords_ = function(aX, aY) {
  784.     var m = this.m_;
  785.     return {
  786.       x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2,
  787.       y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2
  788.     }
  789.   };
  790.  
  791.   contextPrototype.save = function() {
  792.     var o = {};
  793.     copyState(this, o);
  794.     this.aStack_.push(o);
  795.     this.mStack_.push(this.m_);
  796.     this.m_ = matrixMultiply(createMatrixIdentity(), this.m_);
  797.   };
  798.  
  799.   contextPrototype.restore = function() {
  800.     copyState(this.aStack_.pop(), this);
  801.     this.m_ = this.mStack_.pop();
  802.   };
  803.  
  804.   function matrixIsFinite(m) {
  805.     for (var j = 0; j < 3; j++) {
  806.       for (var k = 0; k < 2; k++) {
  807.         if (!isFinite(m[j][k]) || isNaN(m[j][k])) {
  808.           return false;
  809.         }
  810.       }
  811.     }
  812.     return true;
  813.   }
  814.  
  815.   function setM(ctx, m, updateLineScale) {
  816.     if (!matrixIsFinite(m)) {
  817.       return;
  818.     }
  819.     ctx.m_ = m;
  820.  
  821.     if (updateLineScale) {
  822.       // Get the line scale.
  823.       // Determinant of this.m_ means how much the area is enlarged by the
  824.       // transformation. So its square root can be used as a scale factor
  825.       // for width.
  826.       var det = m[0][0] * m[1][1] - m[0][1] * m[1][0];
  827.       ctx.lineScale_ = sqrt(abs(det));
  828.     }
  829.   }
  830.  
  831.   contextPrototype.translate = function(aX, aY) {
  832.     var m1 = [
  833.       [1,  0,  0],
  834.       [0,  1,  0],
  835.       [aX, aY, 1]
  836.     ];
  837.  
  838.     setM(this, matrixMultiply(m1, this.m_), false);
  839.   };
  840.  
  841.   contextPrototype.rotate = function(aRot) {
  842.     var c = mc(aRot);
  843.     var s = ms(aRot);
  844.  
  845.     var m1 = [
  846.       [c,  s, 0],
  847.       [-s, c, 0],
  848.       [0,  0, 1]
  849.     ];
  850.  
  851.     setM(this, matrixMultiply(m1, this.m_), false);
  852.   };
  853.  
  854.   contextPrototype.scale = function(aX, aY) {
  855.     this.arcScaleX_ *= aX;
  856.     this.arcScaleY_ *= aY;
  857.     var m1 = [
  858.       [aX, 0,  0],
  859.       [0,  aY, 0],
  860.       [0,  0,  1]
  861.     ];
  862.  
  863.     setM(this, matrixMultiply(m1, this.m_), true);
  864.   };
  865.  
  866.   contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) {
  867.     var m1 = [
  868.       [m11, m12, 0],
  869.       [m21, m22, 0],
  870.       [dx,  dy,  1]
  871.     ];
  872.  
  873.     setM(this, matrixMultiply(m1, this.m_), true);
  874.   };
  875.  
  876.   contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) {
  877.     var m = [
  878.       [m11, m12, 0],
  879.       [m21, m22, 0],
  880.       [dx,  dy,  1]
  881.     ];
  882.  
  883.     setM(this, m, true);
  884.   };
  885.  
  886.   /******** STUBS ********/
  887.   contextPrototype.clip = function() {
  888.     // TODO: Implement
  889.   };
  890.  
  891.   contextPrototype.arcTo = function() {
  892.     // TODO: Implement
  893.   };
  894.  
  895.   contextPrototype.createPattern = function() {
  896.     return new CanvasPattern_;
  897.   };
  898.  
  899.   // Gradient / Pattern Stubs
  900.   function CanvasGradient_(aType) {
  901.     this.type_ = aType;
  902.     this.x0_ = 0;
  903.     this.y0_ = 0;
  904.     this.r0_ = 0;
  905.     this.x1_ = 0;
  906.     this.y1_ = 0;
  907.     this.r1_ = 0;
  908.     this.colors_ = [];
  909.   }
  910.  
  911.   CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) {
  912.     aColor = processStyle(aColor);
  913.     this.colors_.push({offset: aOffset,
  914.                        color: aColor.color,
  915.                        alpha: aColor.alpha});
  916.   };
  917.  
  918.   function CanvasPattern_() {}
  919.  
  920.   // set up externs
  921.   G_vmlCanvasManager = G_vmlCanvasManager_;
  922.   CanvasRenderingContext2D = CanvasRenderingContext2D_;
  923.   CanvasGradient = CanvasGradient_;
  924.   CanvasPattern = CanvasPattern_;
  925.  
  926. })();
  927.  
  928. } // if
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement