Subversion Repositories Code-Repo

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
141 Kevin 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 only support repeat.
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
(function() {
38
 
39
  // alias some functions to make (compiled) code shorter
40
  var m = Math;
41
  var mr = m.round;
42
  var ms = m.sin;
43
  var mc = m.cos;
44
  var abs = m.abs;
45
  var sqrt = m.sqrt;
46
 
47
  // this is used for sub pixel precision
48
  var Z = 10;
49
  var Z2 = Z / 2;
50
 
51
  /**
52
   * This funtion is assigned to the <canvas> elements as element.getContext().
53
   * @this {HTMLElement}
54
   * @return {CanvasRenderingContext2D_}
55
   */
56
  function getContext() {
57
    return this.context_ ||
58
        (this.context_ = new CanvasRenderingContext2D_(this));
59
  }
60
 
61
  var slice = Array.prototype.slice;
62
 
63
  /**
64
   * Binds a function to an object. The returned function will always use the
65
   * passed in {@code obj} as {@code this}.
66
   *
67
   * Example:
68
   *
69
   *   g = bind(f, obj, a, b)
70
   *   g(c, d) // will do f.call(obj, a, b, c, d)
71
   *
72
   * @param {Function} f The function to bind the object to
73
   * @param {Object} obj The object that should act as this when the function
74
   *     is called
75
   * @param {*} var_args Rest arguments that will be used as the initial
76
   *     arguments when the function is called
77
   * @return {Function} A new function that has bound this
78
   */
79
  function bind(f, obj, var_args) {
80
    var a = slice.call(arguments, 2);
81
    return function() {
82
      return f.apply(obj, a.concat(slice.call(arguments)));
83
    };
84
  }
85
 
86
  function encodeHtmlAttribute(s) {
87
    return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
88
  }
89
 
90
  function addNamespacesAndStylesheet(doc) {
91
    // create xmlns
92
    if (!doc.namespaces['g_vml_']) {
93
      doc.namespaces.add('g_vml_', 'urn:schemas-microsoft-com:vml',
94
                         '#default#VML');
95
 
96
    }
97
    if (!doc.namespaces['g_o_']) {
98
      doc.namespaces.add('g_o_', 'urn:schemas-microsoft-com:office:office',
99
                         '#default#VML');
100
    }
101
 
102
    // Setup default CSS.  Only add one style sheet per document
103
    if (!doc.styleSheets['ex_canvas_']) {
104
      var ss = doc.createStyleSheet();
105
      ss.owningElement.id = 'ex_canvas_';
106
      ss.cssText = 'canvas{display:inline-block;overflow:hidden;' +
107
          // default size is 300x150 in Gecko and Opera
108
          'text-align:left;width:300px;height:150px}';
109
    }
110
  }
111
 
112
  // Add namespaces and stylesheet at startup.
113
  addNamespacesAndStylesheet(document);
114
 
115
  var G_vmlCanvasManager_ = {
116
    init: function(opt_doc) {
117
      if (/MSIE/.test(navigator.userAgent) && !window.opera) {
118
        var doc = opt_doc || document;
119
        // Create a dummy element so that IE will allow canvas elements to be
120
        // recognized.
121
        doc.createElement('canvas');
122
        doc.attachEvent('onreadystatechange', bind(this.init_, this, doc));
123
      }
124
    },
125
 
126
    init_: function(doc) {
127
      // find all canvas elements
128
      var els = doc.getElementsByTagName('canvas');
129
      for (var i = 0; i < els.length; i++) {
130
        this.initElement(els[i]);
131
      }
132
    },
133
 
134
    /**
135
     * Public initializes a canvas element so that it can be used as canvas
136
     * element from now on. This is called automatically before the page is
137
     * loaded but if you are creating elements using createElement you need to
138
     * make sure this is called on the element.
139
     * @param {HTMLElement} el The canvas element to initialize.
140
     * @return {HTMLElement} the element that was created.
141
     */
142
    initElement: function(el) {
143
      if (!el.getContext) {
144
        el.getContext = getContext;
145
 
146
        // Add namespaces and stylesheet to document of the element.
147
        addNamespacesAndStylesheet(el.ownerDocument);
148
 
149
        // Remove fallback content. There is no way to hide text nodes so we
150
        // just remove all childNodes. We could hide all elements and remove
151
        // text nodes but who really cares about the fallback content.
152
        el.innerHTML = '';
153
 
154
        // do not use inline function because that will leak memory
155
        el.attachEvent('onpropertychange', onPropertyChange);
156
        el.attachEvent('onresize', onResize);
157
 
158
        var attrs = el.attributes;
159
        if (attrs.width && attrs.width.specified) {
160
          // TODO: use runtimeStyle and coordsize
161
          // el.getContext().setWidth_(attrs.width.nodeValue);
162
          el.style.width = attrs.width.nodeValue + 'px';
163
        } else {
164
          el.width = el.clientWidth;
165
        }
166
        if (attrs.height && attrs.height.specified) {
167
          // TODO: use runtimeStyle and coordsize
168
          // el.getContext().setHeight_(attrs.height.nodeValue);
169
          el.style.height = attrs.height.nodeValue + 'px';
170
        } else {
171
          el.height = el.clientHeight;
172
        }
173
        //el.getContext().setCoordsize_()
174
      }
175
      return el;
176
    }
177
  };
178
 
179
  function onPropertyChange(e) {
180
    var el = e.srcElement;
181
 
182
    switch (e.propertyName) {
183
      case 'width':
184
        el.getContext().clearRect();
185
        el.style.width = el.attributes.width.nodeValue + 'px';
186
        // In IE8 this does not trigger onresize.
187
        el.firstChild.style.width =  el.clientWidth + 'px';
188
        break;
189
      case 'height':
190
        el.getContext().clearRect();
191
        el.style.height = el.attributes.height.nodeValue + 'px';
192
        el.firstChild.style.height = el.clientHeight + 'px';
193
        break;
194
    }
195
  }
196
 
197
  function onResize(e) {
198
    var el = e.srcElement;
199
    if (el.firstChild) {
200
      el.firstChild.style.width =  el.clientWidth + 'px';
201
      el.firstChild.style.height = el.clientHeight + 'px';
202
    }
203
  }
204
 
205
  G_vmlCanvasManager_.init();
206
 
207
  // precompute "00" to "FF"
208
  var decToHex = [];
209
  for (var i = 0; i < 16; i++) {
210
    for (var j = 0; j < 16; j++) {
211
      decToHex[i * 16 + j] = i.toString(16) + j.toString(16);
212
    }
213
  }
214
 
215
  function createMatrixIdentity() {
216
    return [
217
      [1, 0, 0],
218
      [0, 1, 0],
219
      [0, 0, 1]
220
    ];
221
  }
222
 
223
  function matrixMultiply(m1, m2) {
224
    var result = createMatrixIdentity();
225
 
226
    for (var x = 0; x < 3; x++) {
227
      for (var y = 0; y < 3; y++) {
228
        var sum = 0;
229
 
230
        for (var z = 0; z < 3; z++) {
231
          sum += m1[x][z] * m2[z][y];
232
        }
233
 
234
        result[x][y] = sum;
235
      }
236
    }
237
    return result;
238
  }
239
 
240
  function copyState(o1, o2) {
241
    o2.fillStyle     = o1.fillStyle;
242
    o2.lineCap       = o1.lineCap;
243
    o2.lineJoin      = o1.lineJoin;
244
    o2.lineWidth     = o1.lineWidth;
245
    o2.miterLimit    = o1.miterLimit;
246
    o2.shadowBlur    = o1.shadowBlur;
247
    o2.shadowColor   = o1.shadowColor;
248
    o2.shadowOffsetX = o1.shadowOffsetX;
249
    o2.shadowOffsetY = o1.shadowOffsetY;
250
    o2.strokeStyle   = o1.strokeStyle;
251
    o2.globalAlpha   = o1.globalAlpha;
252
    o2.font          = o1.font;
253
    o2.textAlign     = o1.textAlign;
254
    o2.textBaseline  = o1.textBaseline;
255
    o2.arcScaleX_    = o1.arcScaleX_;
256
    o2.arcScaleY_    = o1.arcScaleY_;
257
    o2.lineScale_    = o1.lineScale_;
258
  }
259
 
260
  var colorData = {
261
    aliceblue: '#F0F8FF',
262
    antiquewhite: '#FAEBD7',
263
    aquamarine: '#7FFFD4',
264
    azure: '#F0FFFF',
265
    beige: '#F5F5DC',
266
    bisque: '#FFE4C4',
267
    black: '#000000',
268
    blanchedalmond: '#FFEBCD',
269
    blueviolet: '#8A2BE2',
270
    brown: '#A52A2A',
271
    burlywood: '#DEB887',
272
    cadetblue: '#5F9EA0',
273
    chartreuse: '#7FFF00',
274
    chocolate: '#D2691E',
275
    coral: '#FF7F50',
276
    cornflowerblue: '#6495ED',
277
    cornsilk: '#FFF8DC',
278
    crimson: '#DC143C',
279
    cyan: '#00FFFF',
280
    darkblue: '#00008B',
281
    darkcyan: '#008B8B',
282
    darkgoldenrod: '#B8860B',
283
    darkgray: '#A9A9A9',
284
    darkgreen: '#006400',
285
    darkgrey: '#A9A9A9',
286
    darkkhaki: '#BDB76B',
287
    darkmagenta: '#8B008B',
288
    darkolivegreen: '#556B2F',
289
    darkorange: '#FF8C00',
290
    darkorchid: '#9932CC',
291
    darkred: '#8B0000',
292
    darksalmon: '#E9967A',
293
    darkseagreen: '#8FBC8F',
294
    darkslateblue: '#483D8B',
295
    darkslategray: '#2F4F4F',
296
    darkslategrey: '#2F4F4F',
297
    darkturquoise: '#00CED1',
298
    darkviolet: '#9400D3',
299
    deeppink: '#FF1493',
300
    deepskyblue: '#00BFFF',
301
    dimgray: '#696969',
302
    dimgrey: '#696969',
303
    dodgerblue: '#1E90FF',
304
    firebrick: '#B22222',
305
    floralwhite: '#FFFAF0',
306
    forestgreen: '#228B22',
307
    gainsboro: '#DCDCDC',
308
    ghostwhite: '#F8F8FF',
309
    gold: '#FFD700',
310
    goldenrod: '#DAA520',
311
    grey: '#808080',
312
    greenyellow: '#ADFF2F',
313
    honeydew: '#F0FFF0',
314
    hotpink: '#FF69B4',
315
    indianred: '#CD5C5C',
316
    indigo: '#4B0082',
317
    ivory: '#FFFFF0',
318
    khaki: '#F0E68C',
319
    lavender: '#E6E6FA',
320
    lavenderblush: '#FFF0F5',
321
    lawngreen: '#7CFC00',
322
    lemonchiffon: '#FFFACD',
323
    lightblue: '#ADD8E6',
324
    lightcoral: '#F08080',
325
    lightcyan: '#E0FFFF',
326
    lightgoldenrodyellow: '#FAFAD2',
327
    lightgreen: '#90EE90',
328
    lightgrey: '#D3D3D3',
329
    lightpink: '#FFB6C1',
330
    lightsalmon: '#FFA07A',
331
    lightseagreen: '#20B2AA',
332
    lightskyblue: '#87CEFA',
333
    lightslategray: '#778899',
334
    lightslategrey: '#778899',
335
    lightsteelblue: '#B0C4DE',
336
    lightyellow: '#FFFFE0',
337
    limegreen: '#32CD32',
338
    linen: '#FAF0E6',
339
    magenta: '#FF00FF',
340
    mediumaquamarine: '#66CDAA',
341
    mediumblue: '#0000CD',
342
    mediumorchid: '#BA55D3',
343
    mediumpurple: '#9370DB',
344
    mediumseagreen: '#3CB371',
345
    mediumslateblue: '#7B68EE',
346
    mediumspringgreen: '#00FA9A',
347
    mediumturquoise: '#48D1CC',
348
    mediumvioletred: '#C71585',
349
    midnightblue: '#191970',
350
    mintcream: '#F5FFFA',
351
    mistyrose: '#FFE4E1',
352
    moccasin: '#FFE4B5',
353
    navajowhite: '#FFDEAD',
354
    oldlace: '#FDF5E6',
355
    olivedrab: '#6B8E23',
356
    orange: '#FFA500',
357
    orangered: '#FF4500',
358
    orchid: '#DA70D6',
359
    palegoldenrod: '#EEE8AA',
360
    palegreen: '#98FB98',
361
    paleturquoise: '#AFEEEE',
362
    palevioletred: '#DB7093',
363
    papayawhip: '#FFEFD5',
364
    peachpuff: '#FFDAB9',
365
    peru: '#CD853F',
366
    pink: '#FFC0CB',
367
    plum: '#DDA0DD',
368
    powderblue: '#B0E0E6',
369
    rosybrown: '#BC8F8F',
370
    royalblue: '#4169E1',
371
    saddlebrown: '#8B4513',
372
    salmon: '#FA8072',
373
    sandybrown: '#F4A460',
374
    seagreen: '#2E8B57',
375
    seashell: '#FFF5EE',
376
    sienna: '#A0522D',
377
    skyblue: '#87CEEB',
378
    slateblue: '#6A5ACD',
379
    slategray: '#708090',
380
    slategrey: '#708090',
381
    snow: '#FFFAFA',
382
    springgreen: '#00FF7F',
383
    steelblue: '#4682B4',
384
    tan: '#D2B48C',
385
    thistle: '#D8BFD8',
386
    tomato: '#FF6347',
387
    turquoise: '#40E0D0',
388
    violet: '#EE82EE',
389
    wheat: '#F5DEB3',
390
    whitesmoke: '#F5F5F5',
391
    yellowgreen: '#9ACD32'
392
  };
393
 
394
 
395
  function getRgbHslContent(styleString) {
396
    var start = styleString.indexOf('(', 3);
397
    var end = styleString.indexOf(')', start + 1);
398
    var parts = styleString.substring(start + 1, end).split(',');
399
    // add alpha if needed
400
    if (parts.length == 4 && styleString.substr(3, 1) == 'a') {
401
      alpha = Number(parts[3]);
402
    } else {
403
      parts[3] = 1;
404
    }
405
    return parts;
406
  }
407
 
408
  function percent(s) {
409
    return parseFloat(s) / 100;
410
  }
411
 
412
  function clamp(v, min, max) {
413
    return Math.min(max, Math.max(min, v));
414
  }
415
 
416
  function hslToRgb(parts){
417
    var r, g, b;
418
    h = parseFloat(parts[0]) / 360 % 360;
419
    if (h < 0)
420
      h++;
421
    s = clamp(percent(parts[1]), 0, 1);
422
    l = clamp(percent(parts[2]), 0, 1);
423
    if (s == 0) {
424
      r = g = b = l; // achromatic
425
    } else {
426
      var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
427
      var p = 2 * l - q;
428
      r = hueToRgb(p, q, h + 1 / 3);
429
      g = hueToRgb(p, q, h);
430
      b = hueToRgb(p, q, h - 1 / 3);
431
    }
432
 
433
    return '#' + decToHex[Math.floor(r * 255)] +
434
        decToHex[Math.floor(g * 255)] +
435
        decToHex[Math.floor(b * 255)];
436
  }
437
 
438
  function hueToRgb(m1, m2, h) {
439
    if (h < 0)
440
      h++;
441
    if (h > 1)
442
      h--;
443
 
444
    if (6 * h < 1)
445
      return m1 + (m2 - m1) * 6 * h;
446
    else if (2 * h < 1)
447
      return m2;
448
    else if (3 * h < 2)
449
      return m1 + (m2 - m1) * (2 / 3 - h) * 6;
450
    else
451
      return m1;
452
  }
453
 
454
  function processStyle(styleString) {
455
    var str, alpha = 1;
456
 
457
    styleString = String(styleString);
458
    if (styleString.charAt(0) == '#') {
459
      str = styleString;
460
    } else if (/^rgb/.test(styleString)) {
461
      var parts = getRgbHslContent(styleString);
462
      var str = '#', n;
463
      for (var i = 0; i < 3; i++) {
464
        if (parts[i].indexOf('%') != -1) {
465
          n = Math.floor(percent(parts[i]) * 255);
466
        } else {
467
          n = Number(parts[i]);
468
        }
469
        str += decToHex[clamp(n, 0, 255)];
470
      }
471
      alpha = parts[3];
472
    } else if (/^hsl/.test(styleString)) {
473
      var parts = getRgbHslContent(styleString);
474
      str = hslToRgb(parts);
475
      alpha = parts[3];
476
    } else {
477
      str = colorData[styleString] || styleString;
478
    }
479
    return {color: str, alpha: alpha};
480
  }
481
 
482
  var DEFAULT_STYLE = {
483
    style: 'normal',
484
    variant: 'normal',
485
    weight: 'normal',
486
    size: 10,
487
    family: 'sans-serif'
488
  };
489
 
490
  // Internal text style cache
491
  var fontStyleCache = {};
492
 
493
  function processFontStyle(styleString) {
494
    if (fontStyleCache[styleString]) {
495
      return fontStyleCache[styleString];
496
    }
497
 
498
    var el = document.createElement('div');
499
    var style = el.style;
500
    try {
501
      style.font = styleString;
502
    } catch (ex) {
503
      // Ignore failures to set to invalid font.
504
    }
505
 
506
    return fontStyleCache[styleString] = {
507
      style: style.fontStyle || DEFAULT_STYLE.style,
508
      variant: style.fontVariant || DEFAULT_STYLE.variant,
509
      weight: style.fontWeight || DEFAULT_STYLE.weight,
510
      size: style.fontSize || DEFAULT_STYLE.size,
511
      family: style.fontFamily || DEFAULT_STYLE.family
512
    };
513
  }
514
 
515
  function getComputedStyle(style, element) {
516
    var computedStyle = {};
517
 
518
    for (var p in style) {
519
      computedStyle[p] = style[p];
520
    }
521
 
522
    // Compute the size
523
    var canvasFontSize = parseFloat(element.currentStyle.fontSize),
524
        fontSize = parseFloat(style.size);
525
 
526
    if (typeof style.size == 'number') {
527
      computedStyle.size = style.size;
528
    } else if (style.size.indexOf('px') != -1) {
529
      computedStyle.size = fontSize;
530
    } else if (style.size.indexOf('em') != -1) {
531
      computedStyle.size = canvasFontSize * fontSize;
532
    } else if(style.size.indexOf('%') != -1) {
533
      computedStyle.size = (canvasFontSize / 100) * fontSize;
534
    } else if (style.size.indexOf('pt') != -1) {
535
      computedStyle.size = canvasFontSize * (4/3) * fontSize;
536
    } else {
537
      computedStyle.size = canvasFontSize;
538
    }
539
 
540
    // Different scaling between normal text and VML text. This was found using
541
    // trial and error to get the same size as non VML text.
542
    computedStyle.size *= 0.981;
543
 
544
    return computedStyle;
545
  }
546
 
547
  function buildStyle(style) {
548
    return style.style + ' ' + style.variant + ' ' + style.weight + ' ' +
549
        style.size + 'px ' + style.family;
550
  }
551
 
552
  function processLineCap(lineCap) {
553
    switch (lineCap) {
554
      case 'butt':
555
        return 'flat';
556
      case 'round':
557
        return 'round';
558
      case 'square':
559
      default:
560
        return 'square';
561
    }
562
  }
563
 
564
  /**
565
   * This class implements CanvasRenderingContext2D interface as described by
566
   * the WHATWG.
567
   * @param {HTMLElement} surfaceElement The element that the 2D context should
568
   * be associated with
569
   */
570
  function CanvasRenderingContext2D_(surfaceElement) {
571
    this.m_ = createMatrixIdentity();
572
 
573
    this.mStack_ = [];
574
    this.aStack_ = [];
575
    this.currentPath_ = [];
576
 
577
    // Canvas context properties
578
    this.strokeStyle = '#000';
579
    this.fillStyle = '#000';
580
 
581
    this.lineWidth = 1;
582
    this.lineJoin = 'miter';
583
    this.lineCap = 'butt';
584
    this.miterLimit = Z * 1;
585
    this.globalAlpha = 1;
586
    this.font = '10px sans-serif';
587
    this.textAlign = 'left';
588
    this.textBaseline = 'alphabetic';
589
    this.canvas = surfaceElement;
590
 
591
    var el = surfaceElement.ownerDocument.createElement('div');
592
    el.style.width =  surfaceElement.clientWidth + 'px';
593
    el.style.height = surfaceElement.clientHeight + 'px';
594
    el.style.overflow = 'hidden';
595
    el.style.position = 'absolute';
596
    surfaceElement.appendChild(el);
597
 
598
    this.element_ = el;
599
    this.arcScaleX_ = 1;
600
    this.arcScaleY_ = 1;
601
    this.lineScale_ = 1;
602
  }
603
 
604
  var contextPrototype = CanvasRenderingContext2D_.prototype;
605
  contextPrototype.clearRect = function() {
606
    if (this.textMeasureEl_) {
607
      this.textMeasureEl_.removeNode(true);
608
      this.textMeasureEl_ = null;
609
    }
610
    this.element_.innerHTML = '';
611
  };
612
 
613
  contextPrototype.beginPath = function() {
614
    // TODO: Branch current matrix so that save/restore has no effect
615
    //       as per safari docs.
616
    this.currentPath_ = [];
617
  };
618
 
619
  contextPrototype.moveTo = function(aX, aY) {
620
    var p = this.getCoords_(aX, aY);
621
    this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y});
622
    this.currentX_ = p.x;
623
    this.currentY_ = p.y;
624
  };
625
 
626
  contextPrototype.lineTo = function(aX, aY) {
627
    var p = this.getCoords_(aX, aY);
628
    this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y});
629
 
630
    this.currentX_ = p.x;
631
    this.currentY_ = p.y;
632
  };
633
 
634
  contextPrototype.bezierCurveTo = function(aCP1x, aCP1y,
635
                                            aCP2x, aCP2y,
636
                                            aX, aY) {
637
    var p = this.getCoords_(aX, aY);
638
    var cp1 = this.getCoords_(aCP1x, aCP1y);
639
    var cp2 = this.getCoords_(aCP2x, aCP2y);
640
    bezierCurveTo(this, cp1, cp2, p);
641
  };
642
 
643
  // Helper function that takes the already fixed cordinates.
644
  function bezierCurveTo(self, cp1, cp2, p) {
645
    self.currentPath_.push({
646
      type: 'bezierCurveTo',
647
      cp1x: cp1.x,
648
      cp1y: cp1.y,
649
      cp2x: cp2.x,
650
      cp2y: cp2.y,
651
      x: p.x,
652
      y: p.y
653
    });
654
    self.currentX_ = p.x;
655
    self.currentY_ = p.y;
656
  }
657
 
658
  contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) {
659
    // the following is lifted almost directly from
660
    // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes
661
 
662
    var cp = this.getCoords_(aCPx, aCPy);
663
    var p = this.getCoords_(aX, aY);
664
 
665
    var cp1 = {
666
      x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_),
667
      y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_)
668
    };
669
    var cp2 = {
670
      x: cp1.x + (p.x - this.currentX_) / 3.0,
671
      y: cp1.y + (p.y - this.currentY_) / 3.0
672
    };
673
 
674
    bezierCurveTo(this, cp1, cp2, p);
675
  };
676
 
677
  contextPrototype.arc = function(aX, aY, aRadius,
678
                                  aStartAngle, aEndAngle, aClockwise) {
679
    aRadius *= Z;
680
    var arcType = aClockwise ? 'at' : 'wa';
681
 
682
    var xStart = aX + mc(aStartAngle) * aRadius - Z2;
683
    var yStart = aY + ms(aStartAngle) * aRadius - Z2;
684
 
685
    var xEnd = aX + mc(aEndAngle) * aRadius - Z2;
686
    var yEnd = aY + ms(aEndAngle) * aRadius - Z2;
687
 
688
    // IE won't render arches drawn counter clockwise if xStart == xEnd.
689
    if (xStart == xEnd && !aClockwise) {
690
      xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something
691
                       // that can be represented in binary
692
    }
693
 
694
    var p = this.getCoords_(aX, aY);
695
    var pStart = this.getCoords_(xStart, yStart);
696
    var pEnd = this.getCoords_(xEnd, yEnd);
697
 
698
    this.currentPath_.push({type: arcType,
699
                           x: p.x,
700
                           y: p.y,
701
                           radius: aRadius,
702
                           xStart: pStart.x,
703
                           yStart: pStart.y,
704
                           xEnd: pEnd.x,
705
                           yEnd: pEnd.y});
706
 
707
  };
708
 
709
  contextPrototype.rect = function(aX, aY, aWidth, aHeight) {
710
    this.moveTo(aX, aY);
711
    this.lineTo(aX + aWidth, aY);
712
    this.lineTo(aX + aWidth, aY + aHeight);
713
    this.lineTo(aX, aY + aHeight);
714
    this.closePath();
715
  };
716
 
717
  contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) {
718
    var oldPath = this.currentPath_;
719
    this.beginPath();
720
 
721
    this.moveTo(aX, aY);
722
    this.lineTo(aX + aWidth, aY);
723
    this.lineTo(aX + aWidth, aY + aHeight);
724
    this.lineTo(aX, aY + aHeight);
725
    this.closePath();
726
    this.stroke();
727
 
728
    this.currentPath_ = oldPath;
729
  };
730
 
731
  contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) {
732
    var oldPath = this.currentPath_;
733
    this.beginPath();
734
 
735
    this.moveTo(aX, aY);
736
    this.lineTo(aX + aWidth, aY);
737
    this.lineTo(aX + aWidth, aY + aHeight);
738
    this.lineTo(aX, aY + aHeight);
739
    this.closePath();
740
    this.fill();
741
 
742
    this.currentPath_ = oldPath;
743
  };
744
 
745
  contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) {
746
    var gradient = new CanvasGradient_('gradient');
747
    gradient.x0_ = aX0;
748
    gradient.y0_ = aY0;
749
    gradient.x1_ = aX1;
750
    gradient.y1_ = aY1;
751
    return gradient;
752
  };
753
 
754
  contextPrototype.createRadialGradient = function(aX0, aY0, aR0,
755
                                                   aX1, aY1, aR1) {
756
    var gradient = new CanvasGradient_('gradientradial');
757
    gradient.x0_ = aX0;
758
    gradient.y0_ = aY0;
759
    gradient.r0_ = aR0;
760
    gradient.x1_ = aX1;
761
    gradient.y1_ = aY1;
762
    gradient.r1_ = aR1;
763
    return gradient;
764
  };
765
 
766
  contextPrototype.drawImage = function(image, var_args) {
767
    var dx, dy, dw, dh, sx, sy, sw, sh;
768
 
769
    // to find the original width we overide the width and height
770
    var oldRuntimeWidth = image.runtimeStyle.width;
771
    var oldRuntimeHeight = image.runtimeStyle.height;
772
    image.runtimeStyle.width = 'auto';
773
    image.runtimeStyle.height = 'auto';
774
 
775
    // get the original size
776
    var w = image.width;
777
    var h = image.height;
778
 
779
    // and remove overides
780
    image.runtimeStyle.width = oldRuntimeWidth;
781
    image.runtimeStyle.height = oldRuntimeHeight;
782
 
783
    if (arguments.length == 3) {
784
      dx = arguments[1];
785
      dy = arguments[2];
786
      sx = sy = 0;
787
      sw = dw = w;
788
      sh = dh = h;
789
    } else if (arguments.length == 5) {
790
      dx = arguments[1];
791
      dy = arguments[2];
792
      dw = arguments[3];
793
      dh = arguments[4];
794
      sx = sy = 0;
795
      sw = w;
796
      sh = h;
797
    } else if (arguments.length == 9) {
798
      sx = arguments[1];
799
      sy = arguments[2];
800
      sw = arguments[3];
801
      sh = arguments[4];
802
      dx = arguments[5];
803
      dy = arguments[6];
804
      dw = arguments[7];
805
      dh = arguments[8];
806
    } else {
807
      throw Error('Invalid number of arguments');
808
    }
809
 
810
    var d = this.getCoords_(dx, dy);
811
 
812
    var w2 = sw / 2;
813
    var h2 = sh / 2;
814
 
815
    var vmlStr = [];
816
 
817
    var W = 10;
818
    var H = 10;
819
 
820
    // For some reason that I've now forgotten, using divs didn't work
821
    vmlStr.push(' <g_vml_:group',
822
                ' coordsize="', Z * W, ',', Z * H, '"',
823
                ' coordorigin="0,0"' ,
824
                ' style="width:', W, 'px;height:', H, 'px;position:absolute;');
825
 
826
    // If filters are necessary (rotation exists), create them
827
    // filters are bog-slow, so only create them if abbsolutely necessary
828
    // The following check doesn't account for skews (which don't exist
829
    // in the canvas spec (yet) anyway.
830
 
831
    if (this.m_[0][0] != 1 || this.m_[0][1] ||
832
        this.m_[1][1] != 1 || this.m_[1][0]) {
833
      var filter = [];
834
 
835
      // Note the 12/21 reversal
836
      filter.push('M11=', this.m_[0][0], ',',
837
                  'M12=', this.m_[1][0], ',',
838
                  'M21=', this.m_[0][1], ',',
839
                  'M22=', this.m_[1][1], ',',
840
                  'Dx=', mr(d.x / Z), ',',
841
                  'Dy=', mr(d.y / Z), '');
842
 
843
      // Bounding box calculation (need to minimize displayed area so that
844
      // filters don't waste time on unused pixels.
845
      var max = d;
846
      var c2 = this.getCoords_(dx + dw, dy);
847
      var c3 = this.getCoords_(dx, dy + dh);
848
      var c4 = this.getCoords_(dx + dw, dy + dh);
849
 
850
      max.x = m.max(max.x, c2.x, c3.x, c4.x);
851
      max.y = m.max(max.y, c2.y, c3.y, c4.y);
852
 
853
      vmlStr.push('padding:0 ', mr(max.x / Z), 'px ', mr(max.y / Z),
854
                  'px 0;filter:progid:DXImageTransform.Microsoft.Matrix(',
855
                  filter.join(''), ", sizingmethod='clip');");
856
 
857
    } else {
858
      vmlStr.push('top:', mr(d.y / Z), 'px;left:', mr(d.x / Z), 'px;');
859
    }
860
 
861
    vmlStr.push(' ">' ,
862
                '<g_vml_:image src="', image.src, '"',
863
                ' style="width:', Z * dw, 'px;',
864
                ' height:', Z * dh, 'px"',
865
                ' cropleft="', sx / w, '"',
866
                ' croptop="', sy / h, '"',
867
                ' cropright="', (w - sx - sw) / w, '"',
868
                ' cropbottom="', (h - sy - sh) / h, '"',
869
                ' />',
870
                '</g_vml_:group>');
871
 
872
    this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join(''));
873
  };
874
 
875
  contextPrototype.stroke = function(aFill) {
876
    var lineStr = [];
877
    var lineOpen = false;
878
 
879
    var W = 10;
880
    var H = 10;
881
 
882
    lineStr.push('<g_vml_:shape',
883
                 ' filled="', !!aFill, '"',
884
                 ' style="position:absolute;width:', W, 'px;height:', H, 'px;"',
885
                 ' coordorigin="0,0"',
886
                 ' coordsize="', Z * W, ',', Z * H, '"',
887
                 ' stroked="', !aFill, '"',
888
                 ' path="');
889
 
890
    var newSeq = false;
891
    var min = {x: null, y: null};
892
    var max = {x: null, y: null};
893
 
894
    for (var i = 0; i < this.currentPath_.length; i++) {
895
      var p = this.currentPath_[i];
896
      var c;
897
 
898
      switch (p.type) {
899
        case 'moveTo':
900
          c = p;
901
          lineStr.push(' m ', mr(p.x), ',', mr(p.y));
902
          break;
903
        case 'lineTo':
904
          lineStr.push(' l ', mr(p.x), ',', mr(p.y));
905
          break;
906
        case 'close':
907
          lineStr.push(' x ');
908
          p = null;
909
          break;
910
        case 'bezierCurveTo':
911
          lineStr.push(' c ',
912
                       mr(p.cp1x), ',', mr(p.cp1y), ',',
913
                       mr(p.cp2x), ',', mr(p.cp2y), ',',
914
                       mr(p.x), ',', mr(p.y));
915
          break;
916
        case 'at':
917
        case 'wa':
918
          lineStr.push(' ', p.type, ' ',
919
                       mr(p.x - this.arcScaleX_ * p.radius), ',',
920
                       mr(p.y - this.arcScaleY_ * p.radius), ' ',
921
                       mr(p.x + this.arcScaleX_ * p.radius), ',',
922
                       mr(p.y + this.arcScaleY_ * p.radius), ' ',
923
                       mr(p.xStart), ',', mr(p.yStart), ' ',
924
                       mr(p.xEnd), ',', mr(p.yEnd));
925
          break;
926
      }
927
 
928
 
929
      // TODO: Following is broken for curves due to
930
      //       move to proper paths.
931
 
932
      // Figure out dimensions so we can do gradient fills
933
      // properly
934
      if (p) {
935
        if (min.x == null || p.x < min.x) {
936
          min.x = p.x;
937
        }
938
        if (max.x == null || p.x > max.x) {
939
          max.x = p.x;
940
        }
941
        if (min.y == null || p.y < min.y) {
942
          min.y = p.y;
943
        }
944
        if (max.y == null || p.y > max.y) {
945
          max.y = p.y;
946
        }
947
      }
948
    }
949
    lineStr.push(' ">');
950
 
951
    if (!aFill) {
952
      appendStroke(this, lineStr);
953
    } else {
954
      appendFill(this, lineStr, min, max);
955
    }
956
 
957
    lineStr.push('</g_vml_:shape>');
958
 
959
    this.element_.insertAdjacentHTML('beforeEnd', lineStr.join(''));
960
  };
961
 
962
  function appendStroke(ctx, lineStr) {
963
    var a = processStyle(ctx.strokeStyle);
964
    var color = a.color;
965
    var opacity = a.alpha * ctx.globalAlpha;
966
    var lineWidth = ctx.lineScale_ * ctx.lineWidth;
967
 
968
    // VML cannot correctly render a line if the width is less than 1px.
969
    // In that case, we dilute the color to make the line look thinner.
970
    if (lineWidth < 1) {
971
      opacity *= lineWidth;
972
    }
973
 
974
    lineStr.push(
975
      '<g_vml_:stroke',
976
      ' opacity="', opacity, '"',
977
      ' joinstyle="', ctx.lineJoin, '"',
978
      ' miterlimit="', ctx.miterLimit, '"',
979
      ' endcap="', processLineCap(ctx.lineCap), '"',
980
      ' weight="', lineWidth, 'px"',
981
      ' color="', color, '" />'
982
    );
983
  }
984
 
985
  function appendFill(ctx, lineStr, min, max) {
986
    var fillStyle = ctx.fillStyle;
987
    var arcScaleX = ctx.arcScaleX_;
988
    var arcScaleY = ctx.arcScaleY_;
989
    var width = max.x - min.x;
990
    var height = max.y - min.y;
991
    if (fillStyle instanceof CanvasGradient_) {
992
      // TODO: Gradients transformed with the transformation matrix.
993
      var angle = 0;
994
      var focus = {x: 0, y: 0};
995
 
996
      // additional offset
997
      var shift = 0;
998
      // scale factor for offset
999
      var expansion = 1;
1000
 
1001
      if (fillStyle.type_ == 'gradient') {
1002
        var x0 = fillStyle.x0_ / arcScaleX;
1003
        var y0 = fillStyle.y0_ / arcScaleY;
1004
        var x1 = fillStyle.x1_ / arcScaleX;
1005
        var y1 = fillStyle.y1_ / arcScaleY;
1006
        var p0 = ctx.getCoords_(x0, y0);
1007
        var p1 = ctx.getCoords_(x1, y1);
1008
        var dx = p1.x - p0.x;
1009
        var dy = p1.y - p0.y;
1010
        angle = Math.atan2(dx, dy) * 180 / Math.PI;
1011
 
1012
        // The angle should be a non-negative number.
1013
        if (angle < 0) {
1014
          angle += 360;
1015
        }
1016
 
1017
        // Very small angles produce an unexpected result because they are
1018
        // converted to a scientific notation string.
1019
        if (angle < 1e-6) {
1020
          angle = 0;
1021
        }
1022
      } else {
1023
        var p0 = ctx.getCoords_(fillStyle.x0_, fillStyle.y0_);
1024
        focus = {
1025
          x: (p0.x - min.x) / width,
1026
          y: (p0.y - min.y) / height
1027
        };
1028
 
1029
        width  /= arcScaleX * Z;
1030
        height /= arcScaleY * Z;
1031
        var dimension = m.max(width, height);
1032
        shift = 2 * fillStyle.r0_ / dimension;
1033
        expansion = 2 * fillStyle.r1_ / dimension - shift;
1034
      }
1035
 
1036
      // We need to sort the color stops in ascending order by offset,
1037
      // otherwise IE won't interpret it correctly.
1038
      var stops = fillStyle.colors_;
1039
      stops.sort(function(cs1, cs2) {
1040
        return cs1.offset - cs2.offset;
1041
      });
1042
 
1043
      var length = stops.length;
1044
      var color1 = stops[0].color;
1045
      var color2 = stops[length - 1].color;
1046
      var opacity1 = stops[0].alpha * ctx.globalAlpha;
1047
      var opacity2 = stops[length - 1].alpha * ctx.globalAlpha;
1048
 
1049
      var colors = [];
1050
      for (var i = 0; i < length; i++) {
1051
        var stop = stops[i];
1052
        colors.push(stop.offset * expansion + shift + ' ' + stop.color);
1053
      }
1054
 
1055
      // When colors attribute is used, the meanings of opacity and o:opacity2
1056
      // are reversed.
1057
      lineStr.push('<g_vml_:fill type="', fillStyle.type_, '"',
1058
                   ' method="none" focus="100%"',
1059
                   ' color="', color1, '"',
1060
                   ' color2="', color2, '"',
1061
                   ' colors="', colors.join(','), '"',
1062
                   ' opacity="', opacity2, '"',
1063
                   ' g_o_:opacity2="', opacity1, '"',
1064
                   ' angle="', angle, '"',
1065
                   ' focusposition="', focus.x, ',', focus.y, '" />');
1066
    } else if (fillStyle instanceof CanvasPattern_) {
1067
      if (width && height) {
1068
        var deltaLeft = -min.x;
1069
        var deltaTop = -min.y;
1070
        lineStr.push('<g_vml_:fill',
1071
                     ' position="',
1072
                     deltaLeft / width * arcScaleX * arcScaleX, ',',
1073
                     deltaTop / height * arcScaleY * arcScaleY, '"',
1074
                     ' type="tile"',
1075
                     // TODO: Figure out the correct size to fit the scale.
1076
                     //' size="', w, 'px ', h, 'px"',
1077
                     ' src="', fillStyle.src_, '" />');
1078
       }
1079
    } else {
1080
      var a = processStyle(ctx.fillStyle);
1081
      var color = a.color;
1082
      var opacity = a.alpha * ctx.globalAlpha;
1083
      lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity,
1084
                   '" />');
1085
    }
1086
  }
1087
 
1088
  contextPrototype.fill = function() {
1089
    this.stroke(true);
1090
  };
1091
 
1092
  contextPrototype.closePath = function() {
1093
    this.currentPath_.push({type: 'close'});
1094
  };
1095
 
1096
  /**
1097
   * @private
1098
   */
1099
  contextPrototype.getCoords_ = function(aX, aY) {
1100
    var m = this.m_;
1101
    return {
1102
      x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2,
1103
      y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2
1104
    };
1105
  };
1106
 
1107
  contextPrototype.save = function() {
1108
    var o = {};
1109
    copyState(this, o);
1110
    this.aStack_.push(o);
1111
    this.mStack_.push(this.m_);
1112
    this.m_ = matrixMultiply(createMatrixIdentity(), this.m_);
1113
  };
1114
 
1115
  contextPrototype.restore = function() {
1116
    if (this.aStack_.length) {
1117
      copyState(this.aStack_.pop(), this);
1118
      this.m_ = this.mStack_.pop();
1119
    }
1120
  };
1121
 
1122
  function matrixIsFinite(m) {
1123
    return isFinite(m[0][0]) && isFinite(m[0][1]) &&
1124
        isFinite(m[1][0]) && isFinite(m[1][1]) &&
1125
        isFinite(m[2][0]) && isFinite(m[2][1]);
1126
  }
1127
 
1128
  function setM(ctx, m, updateLineScale) {
1129
    if (!matrixIsFinite(m)) {
1130
      return;
1131
    }
1132
    ctx.m_ = m;
1133
 
1134
    if (updateLineScale) {
1135
      // Get the line scale.
1136
      // Determinant of this.m_ means how much the area is enlarged by the
1137
      // transformation. So its square root can be used as a scale factor
1138
      // for width.
1139
      var det = m[0][0] * m[1][1] - m[0][1] * m[1][0];
1140
      ctx.lineScale_ = sqrt(abs(det));
1141
    }
1142
  }
1143
 
1144
  contextPrototype.translate = function(aX, aY) {
1145
    var m1 = [
1146
      [1,  0,  0],
1147
      [0,  1,  0],
1148
      [aX, aY, 1]
1149
    ];
1150
 
1151
    setM(this, matrixMultiply(m1, this.m_), false);
1152
  };
1153
 
1154
  contextPrototype.rotate = function(aRot) {
1155
    var c = mc(aRot);
1156
    var s = ms(aRot);
1157
 
1158
    var m1 = [
1159
      [c,  s, 0],
1160
      [-s, c, 0],
1161
      [0,  0, 1]
1162
    ];
1163
 
1164
    setM(this, matrixMultiply(m1, this.m_), false);
1165
  };
1166
 
1167
  contextPrototype.scale = function(aX, aY) {
1168
    this.arcScaleX_ *= aX;
1169
    this.arcScaleY_ *= aY;
1170
    var m1 = [
1171
      [aX, 0,  0],
1172
      [0,  aY, 0],
1173
      [0,  0,  1]
1174
    ];
1175
 
1176
    setM(this, matrixMultiply(m1, this.m_), true);
1177
  };
1178
 
1179
  contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) {
1180
    var m1 = [
1181
      [m11, m12, 0],
1182
      [m21, m22, 0],
1183
      [dx,  dy,  1]
1184
    ];
1185
 
1186
    setM(this, matrixMultiply(m1, this.m_), true);
1187
  };
1188
 
1189
  contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) {
1190
    var m = [
1191
      [m11, m12, 0],
1192
      [m21, m22, 0],
1193
      [dx,  dy,  1]
1194
    ];
1195
 
1196
    setM(this, m, true);
1197
  };
1198
 
1199
  /**
1200
   * The text drawing function.
1201
   * The maxWidth argument isn't taken in account, since no browser supports
1202
   * it yet.
1203
   */
1204
  contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) {
1205
    var m = this.m_,
1206
        delta = 1000,
1207
        left = 0,
1208
        right = delta,
1209
        offset = {x: 0, y: 0},
1210
        lineStr = [];
1211
 
1212
    var fontStyle = getComputedStyle(processFontStyle(this.font),
1213
                                     this.element_);
1214
 
1215
    var fontStyleString = buildStyle(fontStyle);
1216
 
1217
    var elementStyle = this.element_.currentStyle;
1218
    var textAlign = this.textAlign.toLowerCase();
1219
    switch (textAlign) {
1220
      case 'left':
1221
      case 'center':
1222
      case 'right':
1223
        break;
1224
      case 'end':
1225
        textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left';
1226
        break;
1227
      case 'start':
1228
        textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left';
1229
        break;
1230
      default:
1231
        textAlign = 'left';
1232
    }
1233
 
1234
    // 1.75 is an arbitrary number, as there is no info about the text baseline
1235
    switch (this.textBaseline) {
1236
      case 'hanging':
1237
      case 'top':
1238
        offset.y = fontStyle.size / 1.75;
1239
        break;
1240
      case 'middle':
1241
        break;
1242
      default:
1243
      case null:
1244
      case 'alphabetic':
1245
      case 'ideographic':
1246
      case 'bottom':
1247
        offset.y = -fontStyle.size / 2.25;
1248
        break;
1249
    }
1250
 
1251
    switch(textAlign) {
1252
      case 'right':
1253
        left = delta;
1254
        right = 0.05;
1255
        break;
1256
      case 'center':
1257
        left = right = delta / 2;
1258
        break;
1259
    }
1260
 
1261
    var d = this.getCoords_(x + offset.x, y + offset.y);
1262
 
1263
    lineStr.push('<g_vml_:line from="', -left ,' 0" to="', right ,' 0.05" ',
1264
                 ' coordsize="100 100" coordorigin="0 0"',
1265
                 ' filled="', !stroke, '" stroked="', !!stroke,
1266
                 '" style="position:absolute;width:1px;height:1px;">');
1267
 
1268
    if (stroke) {
1269
      appendStroke(this, lineStr);
1270
    } else {
1271
      // TODO: Fix the min and max params.
1272
      appendFill(this, lineStr, {x: -left, y: 0},
1273
                 {x: right, y: fontStyle.size});
1274
    }
1275
 
1276
    var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' +
1277
                m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0';
1278
 
1279
    var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z);
1280
 
1281
    lineStr.push('<g_vml_:skew on="t" matrix="', skewM ,'" ',
1282
                 ' offset="', skewOffset, '" origin="', left ,' 0" />',
1283
                 '<g_vml_:path textpathok="true" />',
1284
                 '<g_vml_:textpath on="true" string="',
1285
                 encodeHtmlAttribute(text),
1286
                 '" style="v-text-align:', textAlign,
1287
                 ';font:', encodeHtmlAttribute(fontStyleString),
1288
                 '" /></g_vml_:line>');
1289
 
1290
    this.element_.insertAdjacentHTML('beforeEnd', lineStr.join(''));
1291
  };
1292
 
1293
  contextPrototype.fillText = function(text, x, y, maxWidth) {
1294
    this.drawText_(text, x, y, maxWidth, false);
1295
  };
1296
 
1297
  contextPrototype.strokeText = function(text, x, y, maxWidth) {
1298
    this.drawText_(text, x, y, maxWidth, true);
1299
  };
1300
 
1301
  contextPrototype.measureText = function(text) {
1302
    if (!this.textMeasureEl_) {
1303
      var s = '<span style="position:absolute;' +
1304
          'top:-20000px;left:0;padding:0;margin:0;border:none;' +
1305
          'white-space:pre;"></span>';
1306
      this.element_.insertAdjacentHTML('beforeEnd', s);
1307
      this.textMeasureEl_ = this.element_.lastChild;
1308
    }
1309
    var doc = this.element_.ownerDocument;
1310
    this.textMeasureEl_.innerHTML = '';
1311
    this.textMeasureEl_.style.font = this.font;
1312
    // Don't use innerHTML or innerText because they allow markup/whitespace.
1313
    this.textMeasureEl_.appendChild(doc.createTextNode(text));
1314
    return {width: this.textMeasureEl_.offsetWidth};
1315
  };
1316
 
1317
  /******** STUBS ********/
1318
  contextPrototype.clip = function() {
1319
    // TODO: Implement
1320
  };
1321
 
1322
  contextPrototype.arcTo = function() {
1323
    // TODO: Implement
1324
  };
1325
 
1326
  contextPrototype.createPattern = function(image, repetition) {
1327
    return new CanvasPattern_(image, repetition);
1328
  };
1329
 
1330
  // Gradient / Pattern Stubs
1331
  function CanvasGradient_(aType) {
1332
    this.type_ = aType;
1333
    this.x0_ = 0;
1334
    this.y0_ = 0;
1335
    this.r0_ = 0;
1336
    this.x1_ = 0;
1337
    this.y1_ = 0;
1338
    this.r1_ = 0;
1339
    this.colors_ = [];
1340
  }
1341
 
1342
  CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) {
1343
    aColor = processStyle(aColor);
1344
    this.colors_.push({offset: aOffset,
1345
                       color: aColor.color,
1346
                       alpha: aColor.alpha});
1347
  };
1348
 
1349
  function CanvasPattern_(image, repetition) {
1350
    assertImageIsValid(image);
1351
    switch (repetition) {
1352
      case 'repeat':
1353
      case null:
1354
      case '':
1355
        this.repetition_ = 'repeat';
1356
        break
1357
      case 'repeat-x':
1358
      case 'repeat-y':
1359
      case 'no-repeat':
1360
        this.repetition_ = repetition;
1361
        break;
1362
      default:
1363
        throwException('SYNTAX_ERR');
1364
    }
1365
 
1366
    this.src_ = image.src;
1367
    this.width_ = image.width;
1368
    this.height_ = image.height;
1369
  }
1370
 
1371
  function throwException(s) {
1372
    throw new DOMException_(s);
1373
  }
1374
 
1375
  function assertImageIsValid(img) {
1376
    if (!img || img.nodeType != 1 || img.tagName != 'IMG') {
1377
      throwException('TYPE_MISMATCH_ERR');
1378
    }
1379
    if (img.readyState != 'complete') {
1380
      throwException('INVALID_STATE_ERR');
1381
    }
1382
  }
1383
 
1384
  function DOMException_(s) {
1385
    this.code = this[s];
1386
    this.message = s +': DOM Exception ' + this.code;
1387
  }
1388
  var p = DOMException_.prototype = new Error;
1389
  p.INDEX_SIZE_ERR = 1;
1390
  p.DOMSTRING_SIZE_ERR = 2;
1391
  p.HIERARCHY_REQUEST_ERR = 3;
1392
  p.WRONG_DOCUMENT_ERR = 4;
1393
  p.INVALID_CHARACTER_ERR = 5;
1394
  p.NO_DATA_ALLOWED_ERR = 6;
1395
  p.NO_MODIFICATION_ALLOWED_ERR = 7;
1396
  p.NOT_FOUND_ERR = 8;
1397
  p.NOT_SUPPORTED_ERR = 9;
1398
  p.INUSE_ATTRIBUTE_ERR = 10;
1399
  p.INVALID_STATE_ERR = 11;
1400
  p.SYNTAX_ERR = 12;
1401
  p.INVALID_MODIFICATION_ERR = 13;
1402
  p.NAMESPACE_ERR = 14;
1403
  p.INVALID_ACCESS_ERR = 15;
1404
  p.VALIDATION_ERR = 16;
1405
  p.TYPE_MISMATCH_ERR = 17;
1406
 
1407
  // set up externs
1408
  G_vmlCanvasManager = G_vmlCanvasManager_;
1409
  CanvasRenderingContext2D = CanvasRenderingContext2D_;
1410
  CanvasGradient = CanvasGradient_;
1411
  CanvasPattern = CanvasPattern_;
1412
  DOMException = DOMException_;
1413
})();
1414
 
1415
} // if