1 // Memory Leaks patch from http://explorercanvas.googlecode.com/svn/trunk/
3 // ------------------------------------------------------------------
4 // Copyright 2006 Google Inc.
6 // Licensed under the Apache License, Version 2.0 (the "License");
7 // you may not use this file except in compliance with the License.
8 // You may obtain a copy of the License at
10 // http://www.apache.org/licenses/LICENSE-2.0
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
21 // * Patterns only support repeat.
22 // * Radial gradient are not implemented. The VML version of these look very
23 // different from the canvas one.
24 // * Clipping paths are not implemented.
25 // * Coordsize. The width and height attribute have higher priority than the
26 // width and height style values which isn't correct.
27 // * Painting mode isn't implemented.
28 // * Canvas width/height should is using content-box by default. IE in
29 // Quirks mode will draw the canvas using border-box. Either change your
31 // (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype)
32 // or use Box Sizing Behavior from WebFX
33 // (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html)
34 // * Non uniform scaling does not correctly scale strokes.
35 // * Optimize. There is always room for speed improvements.
37 // Only add this code if we do not already have a canvas implementation
38 if (!document.createElement('canvas').getContext) {
42 // alias some functions to make (compiled) code shorter
50 // this is used for sub pixel precision
54 var IE_VERSION = +navigator.userAgent.match(/MSIE ([\d.]+)?/)[1];
57 * This funtion is assigned to the <canvas> elements as element.getContext().
59 * @return {CanvasRenderingContext2D_}
61 function getContext() {
62 return this.context_ ||
63 (this.context_ = new CanvasRenderingContext2D_(this));
66 var slice = Array.prototype.slice;
69 * Binds a function to an object. The returned function will always use the
70 * passed in {@code obj} as {@code this}.
74 * g = bind(f, obj, a, b)
75 * g(c, d) // will do f.call(obj, a, b, c, d)
77 * @param {Function} f The function to bind the object to
78 * @param {Object} obj The object that should act as this when the function
80 * @param {*} var_args Rest arguments that will be used as the initial
81 * arguments when the function is called
82 * @return {Function} A new function that has bound this
84 function bind(f, obj, var_args) {
85 var a = slice.call(arguments, 2);
87 return f.apply(obj, a.concat(slice.call(arguments)));
91 function encodeHtmlAttribute(s) {
92 return String(s).replace(/&/g, '&').replace(/"/g, '"');
95 function addNamespace(doc, prefix, urn) {
96 if (!doc.namespaces[prefix]) {
97 doc.namespaces.add(prefix, urn, '#default#VML');
101 function addNamespacesAndStylesheet(doc) {
102 addNamespace(doc, 'g_vml_', 'urn:schemas-microsoft-com:vml');
103 addNamespace(doc, 'g_o_', 'urn:schemas-microsoft-com:office:office');
105 // Setup default CSS. Only add one style sheet per document
106 if (!doc.styleSheets['ex_canvas_']) {
107 var ss = doc.createStyleSheet();
108 ss.owningElement.id = 'ex_canvas_';
109 ss.cssText = 'canvas{display:inline-block;overflow:hidden;' +
110 // default size is 300x150 in Gecko and Opera
111 'text-align:left;width:300px;height:150px}';
115 // Add namespaces and stylesheet at startup.
116 addNamespacesAndStylesheet(document);
118 var G_vmlCanvasManager_ = {
119 init: function(opt_doc) {
120 var doc = opt_doc || document;
121 // Create a dummy element so that IE will allow canvas elements to be
123 doc.createElement('canvas');
124 doc.attachEvent('onreadystatechange', bind(this.init_, this, doc));
127 init_: function(doc) {
128 // find all canvas elements
129 var els = doc.getElementsByTagName('canvas');
130 for (var i = 0; i < els.length; i++) {
131 this.initElement(els[i]);
136 * Public initializes a canvas element so that it can be used as canvas
137 * element from now on. This is called automatically before the page is
138 * loaded but if you are creating elements using createElement you need to
139 * make sure this is called on the element.
140 * @param {HTMLElement} el The canvas element to initialize.
141 * @return {HTMLElement} the element that was created.
143 initElement: function(el) {
144 if (!el.getContext) {
145 el.getContext = getContext;
147 // Add namespaces and stylesheet to document of the element.
148 addNamespacesAndStylesheet(el.ownerDocument);
150 // Remove fallback content. There is no way to hide text nodes so we
151 // just remove all childNodes. We could hide all elements and remove
152 // text nodes but who really cares about the fallback content.
155 // do not use inline function because that will leak memory
156 el.attachEvent('onpropertychange', onPropertyChange);
157 el.attachEvent('onresize', onResize);
159 var attrs = el.attributes;
160 if (attrs.width && attrs.width.specified) {
161 // TODO: use runtimeStyle and coordsize
162 // el.getContext().setWidth_(attrs.width.nodeValue);
163 el.style.width = attrs.width.nodeValue + 'px';
165 el.width = el.clientWidth;
167 if (attrs.height && attrs.height.specified) {
168 // TODO: use runtimeStyle and coordsize
169 // el.getContext().setHeight_(attrs.height.nodeValue);
170 el.style.height = attrs.height.nodeValue + 'px';
172 el.height = el.clientHeight;
174 //el.getContext().setCoordsize_()
179 // Memory Leaks patch : see http://code.google.com/p/explorercanvas/issues/detail?id=82
180 uninitElement: function(el){
182 var ctx = el.getContext();
188 el.getContext = null;
189 el.detachEvent("onpropertychange", onPropertyChange);
190 el.detachEvent("onresize", onResize);
195 function onPropertyChange(e) {
196 var el = e.srcElement;
198 switch (e.propertyName) {
200 el.getContext().clearRect();
201 el.style.width = el.attributes.width.nodeValue + 'px';
202 // In IE8 this does not trigger onresize.
203 el.firstChild.style.width = el.clientWidth + 'px';
206 el.getContext().clearRect();
207 el.style.height = el.attributes.height.nodeValue + 'px';
208 el.firstChild.style.height = el.clientHeight + 'px';
213 function onResize(e) {
214 var el = e.srcElement;
216 el.firstChild.style.width = el.clientWidth + 'px';
217 el.firstChild.style.height = el.clientHeight + 'px';
221 G_vmlCanvasManager_.init();
223 // precompute "00" to "FF"
225 for (var i = 0; i < 16; i++) {
226 for (var j = 0; j < 16; j++) {
227 decToHex[i * 16 + j] = i.toString(16) + j.toString(16);
231 function createMatrixIdentity() {
239 function matrixMultiply(m1, m2) {
240 var result = createMatrixIdentity();
242 for (var x = 0; x < 3; x++) {
243 for (var y = 0; y < 3; y++) {
246 for (var z = 0; z < 3; z++) {
247 sum += m1[x][z] * m2[z][y];
256 function copyState(o1, o2) {
257 o2.fillStyle = o1.fillStyle;
258 o2.lineCap = o1.lineCap;
259 o2.lineJoin = o1.lineJoin;
260 o2.lineWidth = o1.lineWidth;
261 o2.miterLimit = o1.miterLimit;
262 o2.shadowBlur = o1.shadowBlur;
263 o2.shadowColor = o1.shadowColor;
264 o2.shadowOffsetX = o1.shadowOffsetX;
265 o2.shadowOffsetY = o1.shadowOffsetY;
266 o2.strokeStyle = o1.strokeStyle;
267 o2.globalAlpha = o1.globalAlpha;
269 o2.textAlign = o1.textAlign;
270 o2.textBaseline = o1.textBaseline;
271 o2.arcScaleX_ = o1.arcScaleX_;
272 o2.arcScaleY_ = o1.arcScaleY_;
273 o2.lineScale_ = o1.lineScale_;
277 aliceblue: '#F0F8FF',
278 antiquewhite: '#FAEBD7',
279 aquamarine: '#7FFFD4',
284 blanchedalmond: '#FFEBCD',
285 blueviolet: '#8A2BE2',
287 burlywood: '#DEB887',
288 cadetblue: '#5F9EA0',
289 chartreuse: '#7FFF00',
290 chocolate: '#D2691E',
292 cornflowerblue: '#6495ED',
298 darkgoldenrod: '#B8860B',
300 darkgreen: '#006400',
302 darkkhaki: '#BDB76B',
303 darkmagenta: '#8B008B',
304 darkolivegreen: '#556B2F',
305 darkorange: '#FF8C00',
306 darkorchid: '#9932CC',
308 darksalmon: '#E9967A',
309 darkseagreen: '#8FBC8F',
310 darkslateblue: '#483D8B',
311 darkslategray: '#2F4F4F',
312 darkslategrey: '#2F4F4F',
313 darkturquoise: '#00CED1',
314 darkviolet: '#9400D3',
316 deepskyblue: '#00BFFF',
319 dodgerblue: '#1E90FF',
320 firebrick: '#B22222',
321 floralwhite: '#FFFAF0',
322 forestgreen: '#228B22',
323 gainsboro: '#DCDCDC',
324 ghostwhite: '#F8F8FF',
326 goldenrod: '#DAA520',
328 greenyellow: '#ADFF2F',
331 indianred: '#CD5C5C',
336 lavenderblush: '#FFF0F5',
337 lawngreen: '#7CFC00',
338 lemonchiffon: '#FFFACD',
339 lightblue: '#ADD8E6',
340 lightcoral: '#F08080',
341 lightcyan: '#E0FFFF',
342 lightgoldenrodyellow: '#FAFAD2',
343 lightgreen: '#90EE90',
344 lightgrey: '#D3D3D3',
345 lightpink: '#FFB6C1',
346 lightsalmon: '#FFA07A',
347 lightseagreen: '#20B2AA',
348 lightskyblue: '#87CEFA',
349 lightslategray: '#778899',
350 lightslategrey: '#778899',
351 lightsteelblue: '#B0C4DE',
352 lightyellow: '#FFFFE0',
353 limegreen: '#32CD32',
356 mediumaquamarine: '#66CDAA',
357 mediumblue: '#0000CD',
358 mediumorchid: '#BA55D3',
359 mediumpurple: '#9370DB',
360 mediumseagreen: '#3CB371',
361 mediumslateblue: '#7B68EE',
362 mediumspringgreen: '#00FA9A',
363 mediumturquoise: '#48D1CC',
364 mediumvioletred: '#C71585',
365 midnightblue: '#191970',
366 mintcream: '#F5FFFA',
367 mistyrose: '#FFE4E1',
369 navajowhite: '#FFDEAD',
371 olivedrab: '#6B8E23',
373 orangered: '#FF4500',
375 palegoldenrod: '#EEE8AA',
376 palegreen: '#98FB98',
377 paleturquoise: '#AFEEEE',
378 palevioletred: '#DB7093',
379 papayawhip: '#FFEFD5',
380 peachpuff: '#FFDAB9',
384 powderblue: '#B0E0E6',
385 rosybrown: '#BC8F8F',
386 royalblue: '#4169E1',
387 saddlebrown: '#8B4513',
389 sandybrown: '#F4A460',
394 slateblue: '#6A5ACD',
395 slategray: '#708090',
396 slategrey: '#708090',
398 springgreen: '#00FF7F',
399 steelblue: '#4682B4',
403 turquoise: '#40E0D0',
406 whitesmoke: '#F5F5F5',
407 yellowgreen: '#9ACD32'
411 function getRgbHslContent(styleString) {
412 var start = styleString.indexOf('(', 3);
413 var end = styleString.indexOf(')', start + 1);
414 var parts = styleString.substring(start + 1, end).split(',');
415 // add alpha if needed
416 if (parts.length != 4 || styleString.charAt(3) != 'a') {
422 function percent(s) {
423 return parseFloat(s) / 100;
426 function clamp(v, min, max) {
427 return Math.min(max, Math.max(min, v));
430 function hslToRgb(parts){
431 var r, g, b, h, s, l;
432 h = parseFloat(parts[0]) / 360 % 360;
435 s = clamp(percent(parts[1]), 0, 1);
436 l = clamp(percent(parts[2]), 0, 1);
438 r = g = b = l; // achromatic
440 var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
442 r = hueToRgb(p, q, h + 1 / 3);
443 g = hueToRgb(p, q, h);
444 b = hueToRgb(p, q, h - 1 / 3);
447 return '#' + decToHex[Math.floor(r * 255)] +
448 decToHex[Math.floor(g * 255)] +
449 decToHex[Math.floor(b * 255)];
452 function hueToRgb(m1, m2, h) {
459 return m1 + (m2 - m1) * 6 * h;
463 return m1 + (m2 - m1) * (2 / 3 - h) * 6;
468 var processStyleCache = {};
470 function processStyle(styleString) {
471 if (styleString in processStyleCache) {
472 return processStyleCache[styleString];
477 styleString = String(styleString);
478 if (styleString.charAt(0) == '#') {
480 } else if (/^rgb/.test(styleString)) {
481 var parts = getRgbHslContent(styleString);
483 for (var i = 0; i < 3; i++) {
484 if (parts[i].indexOf('%') != -1) {
485 n = Math.floor(percent(parts[i]) * 255);
489 str += decToHex[clamp(n, 0, 255)];
492 } else if (/^hsl/.test(styleString)) {
493 var parts = getRgbHslContent(styleString);
494 str = hslToRgb(parts);
497 str = colorData[styleString] || styleString;
499 return processStyleCache[styleString] = {color: str, alpha: alpha};
502 var DEFAULT_STYLE = {
510 // Internal text style cache
511 var fontStyleCache = {};
513 function processFontStyle(styleString) {
514 if (fontStyleCache[styleString]) {
515 return fontStyleCache[styleString];
518 var el = document.createElement('div');
519 var style = el.style;
521 style.font = styleString;
523 // Ignore failures to set to invalid font.
526 return fontStyleCache[styleString] = {
527 style: style.fontStyle || DEFAULT_STYLE.style,
528 variant: style.fontVariant || DEFAULT_STYLE.variant,
529 weight: style.fontWeight || DEFAULT_STYLE.weight,
530 size: style.fontSize || DEFAULT_STYLE.size,
531 family: style.fontFamily || DEFAULT_STYLE.family
535 function getComputedStyle(style, element) {
536 var computedStyle = {};
538 for (var p in style) {
539 computedStyle[p] = style[p];
543 var canvasFontSize = parseFloat(element.currentStyle.fontSize),
544 fontSize = parseFloat(style.size);
546 if (typeof style.size == 'number') {
547 computedStyle.size = style.size;
548 } else if (style.size.indexOf('px') != -1) {
549 computedStyle.size = fontSize;
550 } else if (style.size.indexOf('em') != -1) {
551 computedStyle.size = canvasFontSize * fontSize;
552 } else if(style.size.indexOf('%') != -1) {
553 computedStyle.size = (canvasFontSize / 100) * fontSize;
554 } else if (style.size.indexOf('pt') != -1) {
555 computedStyle.size = fontSize / .75;
557 computedStyle.size = canvasFontSize;
560 // Different scaling between normal text and VML text. This was found using
561 // trial and error to get the same size as non VML text.
562 computedStyle.size *= 0.981;
564 return computedStyle;
567 function buildStyle(style) {
568 return style.style + ' ' + style.variant + ' ' + style.weight + ' ' +
569 style.size + 'px ' + style.family;
577 function processLineCap(lineCap) {
578 return lineCapMap[lineCap] || 'square';
582 * This class implements CanvasRenderingContext2D interface as described by
584 * @param {HTMLElement} canvasElement The element that the 2D context should
587 function CanvasRenderingContext2D_(canvasElement) {
588 this.m_ = createMatrixIdentity();
592 this.currentPath_ = [];
594 // Canvas context properties
595 this.strokeStyle = '#000';
596 this.fillStyle = '#000';
599 this.lineJoin = 'miter';
600 this.lineCap = 'butt';
601 this.miterLimit = Z * 1;
602 this.globalAlpha = 1;
603 this.font = '10px sans-serif';
604 this.textAlign = 'left';
605 this.textBaseline = 'alphabetic';
606 this.canvas = canvasElement;
608 var cssText = 'width:' + canvasElement.clientWidth + 'px;height:' +
609 canvasElement.clientHeight + 'px;overflow:hidden;position:absolute';
610 var el = canvasElement.ownerDocument.createElement('div');
611 el.style.cssText = cssText;
612 canvasElement.appendChild(el);
614 var overlayEl = el.cloneNode(false);
615 // Use a non transparent background.
616 overlayEl.style.backgroundColor = 'red';
617 overlayEl.style.filter = 'alpha(opacity=0)';
618 canvasElement.appendChild(overlayEl);
626 var contextPrototype = CanvasRenderingContext2D_.prototype;
627 contextPrototype.clearRect = function() {
628 if (this.textMeasureEl_) {
629 this.textMeasureEl_.removeNode(true);
630 this.textMeasureEl_ = null;
632 this.element_.innerHTML = '';
635 contextPrototype.beginPath = function() {
636 // TODO: Branch current matrix so that save/restore has no effect
637 // as per safari docs.
638 this.currentPath_ = [];
641 contextPrototype.moveTo = function(aX, aY) {
642 var p = getCoords(this, aX, aY);
643 this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y});
644 this.currentX_ = p.x;
645 this.currentY_ = p.y;
648 contextPrototype.lineTo = function(aX, aY) {
649 var p = getCoords(this, aX, aY);
650 this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y});
652 this.currentX_ = p.x;
653 this.currentY_ = p.y;
656 contextPrototype.bezierCurveTo = function(aCP1x, aCP1y,
659 var p = getCoords(this, aX, aY);
660 var cp1 = getCoords(this, aCP1x, aCP1y);
661 var cp2 = getCoords(this, aCP2x, aCP2y);
662 bezierCurveTo(this, cp1, cp2, p);
665 // Helper function that takes the already fixed cordinates.
666 function bezierCurveTo(self, cp1, cp2, p) {
667 self.currentPath_.push({
668 type: 'bezierCurveTo',
676 self.currentX_ = p.x;
677 self.currentY_ = p.y;
680 contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) {
681 // the following is lifted almost directly from
682 // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes
684 var cp = getCoords(this, aCPx, aCPy);
685 var p = getCoords(this, aX, aY);
688 x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_),
689 y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_)
692 x: cp1.x + (p.x - this.currentX_) / 3.0,
693 y: cp1.y + (p.y - this.currentY_) / 3.0
696 bezierCurveTo(this, cp1, cp2, p);
699 contextPrototype.arc = function(aX, aY, aRadius,
700 aStartAngle, aEndAngle, aClockwise) {
702 var arcType = aClockwise ? 'at' : 'wa';
704 var xStart = aX + mc(aStartAngle) * aRadius - Z2;
705 var yStart = aY + ms(aStartAngle) * aRadius - Z2;
707 var xEnd = aX + mc(aEndAngle) * aRadius - Z2;
708 var yEnd = aY + ms(aEndAngle) * aRadius - Z2;
710 // IE won't render arches drawn counter clockwise if xStart == xEnd.
711 if (xStart == xEnd && !aClockwise) {
712 xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something
713 // that can be represented in binary
716 var p = getCoords(this, aX, aY);
717 var pStart = getCoords(this, xStart, yStart);
718 var pEnd = getCoords(this, xEnd, yEnd);
720 this.currentPath_.push({type: arcType,
731 contextPrototype.rect = function(aX, aY, aWidth, aHeight) {
733 this.lineTo(aX + aWidth, aY);
734 this.lineTo(aX + aWidth, aY + aHeight);
735 this.lineTo(aX, aY + aHeight);
739 contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) {
740 var oldPath = this.currentPath_;
744 this.lineTo(aX + aWidth, aY);
745 this.lineTo(aX + aWidth, aY + aHeight);
746 this.lineTo(aX, aY + aHeight);
750 this.currentPath_ = oldPath;
753 contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) {
754 var oldPath = this.currentPath_;
758 this.lineTo(aX + aWidth, aY);
759 this.lineTo(aX + aWidth, aY + aHeight);
760 this.lineTo(aX, aY + aHeight);
764 this.currentPath_ = oldPath;
767 contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) {
768 var gradient = new CanvasGradient_('gradient');
776 contextPrototype.createRadialGradient = function(aX0, aY0, aR0,
778 var gradient = new CanvasGradient_('gradientradial');
788 contextPrototype.drawImage = function(image, var_args) {
789 var dx, dy, dw, dh, sx, sy, sw, sh;
791 // to find the original width we overide the width and height
792 var oldRuntimeWidth = image.runtimeStyle.width;
793 var oldRuntimeHeight = image.runtimeStyle.height;
794 image.runtimeStyle.width = 'auto';
795 image.runtimeStyle.height = 'auto';
797 // get the original size
799 var h = image.height;
801 // and remove overides
802 image.runtimeStyle.width = oldRuntimeWidth;
803 image.runtimeStyle.height = oldRuntimeHeight;
805 if (arguments.length == 3) {
811 } else if (arguments.length == 5) {
819 } else if (arguments.length == 9) {
829 throw Error('Invalid number of arguments');
832 var d = getCoords(this, dx, dy);
842 // For some reason that I've now forgotten, using divs didn't work
843 vmlStr.push(' <g_vml_:group',
844 ' coordsize="', Z * W, ',', Z * H, '"',
845 ' coordorigin="0,0"' ,
846 ' style="width:', W, 'px;height:', H, 'px;position:absolute;');
848 // If filters are necessary (rotation exists), create them
849 // filters are bog-slow, so only create them if abbsolutely necessary
850 // The following check doesn't account for skews (which don't exist
851 // in the canvas spec (yet) anyway.
853 if (this.m_[0][0] != 1 || this.m_[0][1] ||
854 this.m_[1][1] != 1 || this.m_[1][0]) {
857 // Note the 12/21 reversal
858 filter.push('M11=', this.m_[0][0], ',',
859 'M12=', this.m_[1][0], ',',
860 'M21=', this.m_[0][1], ',',
861 'M22=', this.m_[1][1], ',',
862 'Dx=', mr(d.x / Z), ',',
863 'Dy=', mr(d.y / Z), '');
865 // Bounding box calculation (need to minimize displayed area so that
866 // filters don't waste time on unused pixels.
868 var c2 = getCoords(this, dx + dw, dy);
869 var c3 = getCoords(this, dx, dy + dh);
870 var c4 = getCoords(this, dx + dw, dy + dh);
872 max.x = m.max(max.x, c2.x, c3.x, c4.x);
873 max.y = m.max(max.y, c2.y, c3.y, c4.y);
875 vmlStr.push('padding:0 ', mr(max.x / Z), 'px ', mr(max.y / Z),
876 'px 0;filter:progid:DXImageTransform.Microsoft.Matrix(',
877 filter.join(''), ", sizingmethod='clip');");
880 vmlStr.push('top:', mr(d.y / Z), 'px;left:', mr(d.x / Z), 'px;');
884 '<g_vml_:image src="', image.src, '"',
885 ' style="width:', Z * dw, 'px;',
886 ' height:', Z * dh, 'px"',
887 ' cropleft="', sx / w, '"',
888 ' croptop="', sy / h, '"',
889 ' cropright="', (w - sx - sw) / w, '"',
890 ' cropbottom="', (h - sy - sh) / h, '"',
894 this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join(''));
897 contextPrototype.stroke = function(aFill) {
899 var lineOpen = false;
904 lineStr.push('<g_vml_:shape',
905 ' filled="', !!aFill, '"',
906 ' style="position:absolute;width:', W, 'px;height:', H, 'px;"',
907 ' coordorigin="0,0"',
908 ' coordsize="', Z * W, ',', Z * H, '"',
909 ' stroked="', !aFill, '"',
913 var min = {x: null, y: null};
914 var max = {x: null, y: null};
916 for (var i = 0; i < this.currentPath_.length; i++) {
917 var p = this.currentPath_[i];
923 lineStr.push(' m ', mr(p.x), ',', mr(p.y));
926 lineStr.push(' l ', mr(p.x), ',', mr(p.y));
932 case 'bezierCurveTo':
934 mr(p.cp1x), ',', mr(p.cp1y), ',',
935 mr(p.cp2x), ',', mr(p.cp2y), ',',
936 mr(p.x), ',', mr(p.y));
940 lineStr.push(' ', p.type, ' ',
941 mr(p.x - this.arcScaleX_ * p.radius), ',',
942 mr(p.y - this.arcScaleY_ * p.radius), ' ',
943 mr(p.x + this.arcScaleX_ * p.radius), ',',
944 mr(p.y + this.arcScaleY_ * p.radius), ' ',
945 mr(p.xStart), ',', mr(p.yStart), ' ',
946 mr(p.xEnd), ',', mr(p.yEnd));
951 // TODO: Following is broken for curves due to
952 // move to proper paths.
954 // Figure out dimensions so we can do gradient fills
957 if (min.x == null || p.x < min.x) {
960 if (max.x == null || p.x > max.x) {
963 if (min.y == null || p.y < min.y) {
966 if (max.y == null || p.y > max.y) {
974 appendStroke(this, lineStr);
976 appendFill(this, lineStr, min, max);
979 lineStr.push('</g_vml_:shape>');
981 this.element_.insertAdjacentHTML('beforeEnd', lineStr.join(''));
984 function appendStroke(ctx, lineStr) {
985 var a = processStyle(ctx.strokeStyle);
987 var opacity = a.alpha * ctx.globalAlpha;
988 var lineWidth = ctx.lineScale_ * ctx.lineWidth;
990 // VML cannot correctly render a line if the width is less than 1px.
991 // In that case, we dilute the color to make the line look thinner.
993 opacity *= lineWidth;
998 ' opacity="', opacity, '"',
999 ' joinstyle="', ctx.lineJoin, '"',
1000 ' miterlimit="', ctx.miterLimit, '"',
1001 ' endcap="', processLineCap(ctx.lineCap), '"',
1002 ' weight="', lineWidth, 'px"',
1003 ' color="', color, '" />'
1007 function appendFill(ctx, lineStr, min, max) {
1008 var fillStyle = ctx.fillStyle;
1009 var arcScaleX = ctx.arcScaleX_;
1010 var arcScaleY = ctx.arcScaleY_;
1011 var width = max.x - min.x;
1012 var height = max.y - min.y;
1013 if (fillStyle instanceof CanvasGradient_) {
1014 // TODO: Gradients transformed with the transformation matrix.
1016 var focus = {x: 0, y: 0};
1018 // additional offset
1020 // scale factor for offset
1023 if (fillStyle.type_ == 'gradient') {
1024 var x0 = fillStyle.x0_ / arcScaleX;
1025 var y0 = fillStyle.y0_ / arcScaleY;
1026 var x1 = fillStyle.x1_ / arcScaleX;
1027 var y1 = fillStyle.y1_ / arcScaleY;
1028 var p0 = getCoords(ctx, x0, y0);
1029 var p1 = getCoords(ctx, x1, y1);
1030 var dx = p1.x - p0.x;
1031 var dy = p1.y - p0.y;
1032 angle = Math.atan2(dx, dy) * 180 / Math.PI;
1034 // The angle should be a non-negative number.
1039 // Very small angles produce an unexpected result because they are
1040 // converted to a scientific notation string.
1045 var p0 = getCoords(ctx, fillStyle.x0_, fillStyle.y0_);
1047 x: (p0.x - min.x) / width,
1048 y: (p0.y - min.y) / height
1051 width /= arcScaleX * Z;
1052 height /= arcScaleY * Z;
1053 var dimension = m.max(width, height);
1054 shift = 2 * fillStyle.r0_ / dimension;
1055 expansion = 2 * fillStyle.r1_ / dimension - shift;
1058 // We need to sort the color stops in ascending order by offset,
1059 // otherwise IE won't interpret it correctly.
1060 var stops = fillStyle.colors_;
1061 stops.sort(function(cs1, cs2) {
1062 return cs1.offset - cs2.offset;
1065 var length = stops.length;
1066 var color1 = stops[0].color;
1067 var color2 = stops[length - 1].color;
1068 var opacity1 = stops[0].alpha * ctx.globalAlpha;
1069 var opacity2 = stops[length - 1].alpha * ctx.globalAlpha;
1072 for (var i = 0; i < length; i++) {
1073 var stop = stops[i];
1074 colors.push(stop.offset * expansion + shift + ' ' + stop.color);
1077 // When colors attribute is used, the meanings of opacity and o:opacity2
1079 lineStr.push('<g_vml_:fill type="', fillStyle.type_, '"',
1080 ' method="none" focus="100%"',
1081 ' color="', color1, '"',
1082 ' color2="', color2, '"',
1083 ' colors="', colors.join(','), '"',
1084 ' opacity="', opacity2, '"',
1085 ' g_o_:opacity2="', opacity1, '"',
1086 ' angle="', angle, '"',
1087 ' focusposition="', focus.x, ',', focus.y, '" />');
1088 } else if (fillStyle instanceof CanvasPattern_) {
1089 if (width && height) {
1090 var deltaLeft = -min.x;
1091 var deltaTop = -min.y;
1092 lineStr.push('<g_vml_:fill',
1094 deltaLeft / width * arcScaleX * arcScaleX, ',',
1095 deltaTop / height * arcScaleY * arcScaleY, '"',
1097 // TODO: Figure out the correct size to fit the scale.
1098 //' size="', w, 'px ', h, 'px"',
1099 ' src="', fillStyle.src_, '" />');
1102 var a = processStyle(ctx.fillStyle);
1103 var color = a.color;
1104 var opacity = a.alpha * ctx.globalAlpha;
1105 lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity,
1110 contextPrototype.fill = function() {
1114 contextPrototype.closePath = function() {
1115 this.currentPath_.push({type: 'close'});
1118 function getCoords(ctx, aX, aY) {
1121 x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2,
1122 y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2
1126 contextPrototype.save = function() {
1129 this.aStack_.push(o);
1130 this.mStack_.push(this.m_);
1131 this.m_ = matrixMultiply(createMatrixIdentity(), this.m_);
1134 contextPrototype.restore = function() {
1135 if (this.aStack_.length) {
1136 copyState(this.aStack_.pop(), this);
1137 this.m_ = this.mStack_.pop();
1141 function matrixIsFinite(m) {
1142 return isFinite(m[0][0]) && isFinite(m[0][1]) &&
1143 isFinite(m[1][0]) && isFinite(m[1][1]) &&
1144 isFinite(m[2][0]) && isFinite(m[2][1]);
1147 function setM(ctx, m, updateLineScale) {
1148 if (!matrixIsFinite(m)) {
1153 if (updateLineScale) {
1154 // Get the line scale.
1155 // Determinant of this.m_ means how much the area is enlarged by the
1156 // transformation. So its square root can be used as a scale factor
1158 var det = m[0][0] * m[1][1] - m[0][1] * m[1][0];
1159 ctx.lineScale_ = sqrt(abs(det));
1163 contextPrototype.translate = function(aX, aY) {
1170 setM(this, matrixMultiply(m1, this.m_), false);
1173 contextPrototype.rotate = function(aRot) {
1183 setM(this, matrixMultiply(m1, this.m_), false);
1186 contextPrototype.scale = function(aX, aY) {
1187 this.arcScaleX_ *= aX;
1188 this.arcScaleY_ *= aY;
1195 setM(this, matrixMultiply(m1, this.m_), true);
1198 contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) {
1205 setM(this, matrixMultiply(m1, this.m_), true);
1208 contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) {
1215 setM(this, m, true);
1219 * The text drawing function.
1220 * The maxWidth argument isn't taken in account, since no browser supports
1223 contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) {
1228 offset = {x: 0, y: 0},
1231 var fontStyle = getComputedStyle(processFontStyle(this.font),
1234 var fontStyleString = buildStyle(fontStyle);
1236 var elementStyle = this.element_.currentStyle;
1237 var textAlign = this.textAlign.toLowerCase();
1238 switch (textAlign) {
1244 textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left';
1247 textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left';
1253 // 1.75 is an arbitrary number, as there is no info about the text baseline
1254 switch (this.textBaseline) {
1257 offset.y = fontStyle.size / 1.75;
1266 offset.y = -fontStyle.size / 2.25;
1276 left = right = delta / 2;
1280 var d = getCoords(this, x + offset.x, y + offset.y);
1282 lineStr.push('<g_vml_:line from="', -left ,' 0" to="', right ,' 0.05" ',
1283 ' coordsize="100 100" coordorigin="0 0"',
1284 ' filled="', !stroke, '" stroked="', !!stroke,
1285 '" style="position:absolute;width:1px;height:1px;">');
1288 appendStroke(this, lineStr);
1290 // TODO: Fix the min and max params.
1291 appendFill(this, lineStr, {x: -left, y: 0},
1292 {x: right, y: fontStyle.size});
1295 var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' +
1296 m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0';
1298 var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z);
1300 lineStr.push('<g_vml_:skew on="t" matrix="', skewM ,'" ',
1301 ' offset="', skewOffset, '" origin="', left ,' 0" />',
1302 '<g_vml_:path textpathok="true" />',
1303 '<g_vml_:textpath on="true" string="',
1304 encodeHtmlAttribute(text),
1305 '" style="v-text-align:', textAlign,
1306 ';font:', encodeHtmlAttribute(fontStyleString),
1307 '" /></g_vml_:line>');
1309 this.element_.insertAdjacentHTML('beforeEnd', lineStr.join(''));
1312 contextPrototype.fillText = function(text, x, y, maxWidth) {
1313 this.drawText_(text, x, y, maxWidth, false);
1316 contextPrototype.strokeText = function(text, x, y, maxWidth) {
1317 this.drawText_(text, x, y, maxWidth, true);
1320 contextPrototype.measureText = function(text) {
1321 if (!this.textMeasureEl_) {
1322 var s = '<span style="position:absolute;' +
1323 'top:-20000px;left:0;padding:0;margin:0;border:none;' +
1324 'white-space:pre;"></span>';
1325 this.element_.insertAdjacentHTML('beforeEnd', s);
1326 this.textMeasureEl_ = this.element_.lastChild;
1328 var doc = this.element_.ownerDocument;
1329 this.textMeasureEl_.innerHTML = '';
1330 this.textMeasureEl_.style.font = this.font;
1331 // Don't use innerHTML or innerText because they allow markup/whitespace.
1332 this.textMeasureEl_.appendChild(doc.createTextNode(text));
1333 return {width: this.textMeasureEl_.offsetWidth};
1336 /******** STUBS ********/
1337 contextPrototype.clip = function() {
1341 contextPrototype.arcTo = function() {
1345 contextPrototype.createPattern = function(image, repetition) {
1346 return new CanvasPattern_(image, repetition);
1349 // Gradient / Pattern Stubs
1350 function CanvasGradient_(aType) {
1361 CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) {
1362 aColor = processStyle(aColor);
1363 this.colors_.push({offset: aOffset,
1364 color: aColor.color,
1365 alpha: aColor.alpha});
1368 function CanvasPattern_(image, repetition) {
1369 assertImageIsValid(image);
1370 switch (repetition) {
1374 this.repetition_ = 'repeat';
1379 this.repetition_ = repetition;
1382 throwException('SYNTAX_ERR');
1385 this.src_ = image.src;
1386 this.width_ = image.width;
1387 this.height_ = image.height;
1390 function throwException(s) {
1391 throw new DOMException_(s);
1394 function assertImageIsValid(img) {
1395 if (!img || img.nodeType != 1 || img.tagName != 'IMG') {
1396 throwException('TYPE_MISMATCH_ERR');
1398 if (img.readyState != 'complete') {
1399 throwException('INVALID_STATE_ERR');
1403 function DOMException_(s) {
1404 this.code = this[s];
1405 this.message = s +': DOM Exception ' + this.code;
1407 var p = DOMException_.prototype = new Error;
1408 p.INDEX_SIZE_ERR = 1;
1409 p.DOMSTRING_SIZE_ERR = 2;
1410 p.HIERARCHY_REQUEST_ERR = 3;
1411 p.WRONG_DOCUMENT_ERR = 4;
1412 p.INVALID_CHARACTER_ERR = 5;
1413 p.NO_DATA_ALLOWED_ERR = 6;
1414 p.NO_MODIFICATION_ALLOWED_ERR = 7;
1415 p.NOT_FOUND_ERR = 8;
1416 p.NOT_SUPPORTED_ERR = 9;
1417 p.INUSE_ATTRIBUTE_ERR = 10;
1418 p.INVALID_STATE_ERR = 11;
1420 p.INVALID_MODIFICATION_ERR = 13;
1421 p.NAMESPACE_ERR = 14;
1422 p.INVALID_ACCESS_ERR = 15;
1423 p.VALIDATION_ERR = 16;
1424 p.TYPE_MISMATCH_ERR = 17;
1427 G_vmlCanvasManager = G_vmlCanvasManager_;
1428 CanvasRenderingContext2D = CanvasRenderingContext2D_;
1429 CanvasGradient = CanvasGradient_;
1430 CanvasPattern = CanvasPattern_;
1431 DOMException = DOMException_;