Debian Codegraph @

silverlight/excanvas.js

raw symbols SCIP
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: (From VML version)
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 // * Coordsize. The width and height attribute have higher priority than the
22 // width and height style values which isn't correct.
23 // * Painting mode isn't implemented.
24 // * Canvas width/height should is using content-box by default. IE in
25 // Quirks mode will draw the canvas using border-box. Either change your
26 // doctype to HTML5
27 // (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype)
28 // or use Box Sizing Behavior from WebFX
29 // (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html)
30 // * Optimize. There is always room for speed improvements.
31
32 //Known Issues: Silverlight version
33 //
34 // * Doing a transformation during a path (ie lineTo, transform, lineTo) will
35 // not work corerctly because the transform is done to the whole path (ie
36 // transform, lineTo, lineTo)
37 // * Patterns are not yet implemented.
38
39
40 // only add this code if we do not already have a canvas implementation
41 if (!window.CanvasRenderingContext2D) {
42
43 (function () {
44
45 var xamlId;
46
47 var G_vmlCanvasManager_ = {
48 init: function (opt_doc) {
49 var doc = opt_doc || document;
50 // Create a dummy element so that IE will allow canvas elements to be
51 // recognized.
52 doc.createElement('canvas');
53 if (/MSIE/.test(navigator.userAgent) && !window.opera) {
54 var self = this;
55
56 createXamlScriptTag();
57
58 doc.attachEvent('onreadystatechange', function () {
59 self.init_(doc);
60 });
61 }
62 },
63
64 init_: function (doc) {
65 // setup default css
66 var ss = doc.createStyleSheet();
67 ss.cssText = 'canvas{display:inline-block;overflow:hidden;' +
68 // default size is 300x150 in Gecko and Opera
69 'text-align:left;width:300px;height:150px}' +
70 'canvas *{width:100%;height:100%;border:0;' +
71 'background:transparen;margin:0}' +
72 'canvas div {position:relative}' +
73 // Place a div on top of the plugin.
74 'canvas div div{position:absolute;top:0;' +
75 // needs to be "non transparent"
76 'filter:alpha(opacity=0);background:red}';
77
78 // find all canvas elements
79 var els = doc.getElementsByTagName('canvas');
80 for (var i = 0; i < els.length; i++) {
81 if (!els[i].getContext) {
82 this.initElement(els[i]);
83 }
84 }
85 },
86
87
88 /**
89 * Public initializes a canvas element so that it can be used as canvas
90 * element from now on. This is called automatically before the page is
91 * loaded but if you are creating elements using createElement you need to
92 * make sure this is called on the element.
93 * @param {HTMLElement} el The canvas element to initialize.
94 * @return {HTMLElement} the element that was created.
95 */
96 initElement: function (el) {
97 el.getContext = function () {
98 if (this.context_) {
99 return this.context_;
100 }
101 return this.context_ = new CanvasRenderingContext2D_(this);
102 };
103
104 var attrs = el.attributes;
105 if (attrs.width && attrs.width.specified) {
106 // TODO: use runtimeStyle and coordsize
107 // el.getContext().setWidth_(attrs.width.nodeValue);
108 el.style.width = attrs.width.nodeValue + 'px';
109 } else {
110 el.width = el.clientWidth;
111 }
112 if (attrs.height && attrs.height.specified) {
113 // TODO: use runtimeStyle and coordsize
114 // el.getContext().setHeight_(attrs.height.nodeValue);
115 el.style.height = attrs.height.nodeValue + 'px';
116 } else {
117 el.height = el.clientHeight;
118 }
119
120 // insert object tag
121 el.innerHTML = getObjectHtml();
122
123 // do not use inline function because that will leak memory
124 el.attachEvent('onpropertychange', onPropertyChange);
125 return el;
126 }
127 };
128
129 function onPropertyChange(e) {
130 var el = e.srcElement;
131
132 switch (e.propertyName) {
133 case 'width':
134 el.style.width = el.attributes.width.nodeValue + 'px';
135 el.getContext().clearRect();
136 break;
137 case 'height':
138 el.style.height = el.attributes.height.nodeValue + 'px';
139 el.getContext().clearRect();
140 break;
141 }
142 }
143
144 G_vmlCanvasManager_.init();
145
146 function createXamlScriptTag() {
147 // This script tag contains the boilerplate XAML.
148 document.write('<script type=text/xaml>' +
149 '<Canvas x:Name="root" ' +
150 'xmlns="http://schemas.microsoft.com/client/2007" ' +
151 'xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" ' +
152 'Width="300" ' +
153 'Height="150" ' +
154 'Background="Transparent"> ' +
155 '</Canvas>' +
156 '</script>');
157 // Find the id of the writtenscript file.
158 var scripts = document.scripts;
159 var script = scripts[scripts.length - 1];
160 xamlId = script.uniqueID;
161 script.id = xamlId;
162 }
163
164 function getObjectHtml(fn) {
165 return '<div><object type="application/x-silverlight" >' +
166 '<param name="windowless" value="true">' +
167 '<param name="background" value="transparent">' +
168 '<param name="source" value="#' + xamlId + '">' +
169 '</object><div></div></div>';
170 }
171
172 function hasSilverlight() {
173 try {
174 new ActiveXObject('AgControl.AgControl');
175 return true;
176 } catch(_) {
177 return false;
178 }
179 }
180
181 // precompute "00" to "FF"
182 var dec2hex = [];
183 for (var i = 0; i < 16; i++) {
184 for (var j = 0; j < 16; j++) {
185 dec2hex[i * 16 + j] = i.toString(16) + j.toString(16);
186 }
187 }
188
189 function createMatrixIdentity() {
190 return [
191 [1, 0, 0],
192 [0, 1, 0],
193 [0, 0, 1]
194 ];
195 }
196
197 function matrixMultiply(m1, m2) {
198 var result = createMatrixIdentity();
199
200 for (var x = 0; x < 3; x++) {
201 for (var y = 0; y < 3; y++) {
202 var sum = 0;
203
204 for (var z = 0; z < 3; z++) {
205 sum += m1[x][z] * m2[z][y];
206 }
207
208 result[x][y] = sum;
209 }
210 }
211 return result;
212 }
213
214 function doTransform(ctx) {
215 transformObject(ctx, getRoot(ctx), ctx.m_);
216 }
217
218 function transformObject(ctx, obj, m) {
219 var transform = obj.renderTransform;
220 var matrix;
221 if (!transform) {
222 transform = create(ctx, '<MatrixTransform/>');
223 matrix = create(ctx, '<Matrix/>');
224 transform.matrix = matrix;
225 obj.renderTransform = transform;
226 } else {
227 matrix = transform.matrix;
228 }
229
230 matrix.m11 = m[0][0];
231 matrix.m12 = m[0][1];
232 matrix.m21 = m[1][0];
233 matrix.m22 = m[1][1];
234 matrix.offsetX = m[2][0];
235 matrix.offsetY = m[2][1];
236 }
237
238 function copyState(o1, o2) {
239 o2.fillStyle = o1.fillStyle;
240 o2.lineCap = o1.lineCap;
241 o2.lineJoin = o1.lineJoin;
242 o2.lineWidth = o1.lineWidth;
243 o2.miterLimit = o1.miterLimit;
244 o2.shadowBlur = o1.shadowBlur;
245 o2.shadowColor = o1.shadowColor;
246 o2.shadowOffsetX = o1.shadowOffsetX;
247 o2.shadowOffsetY = o1.shadowOffsetY;
248 o2.strokeStyle = o1.strokeStyle;
249 o2.globalAlpha = o1.globalAlpha;
250 o2.arcScaleX_ = o1.arcScaleX_;
251 o2.arcScaleY_ = o1.arcScaleY_;
252 }
253
254 // precompute "00" to "FF"
255 var decToHex = [];
256 for (var i = 0; i < 16; i++) {
257 for (var j = 0; j < 16; j++) {
258 decToHex[i * 16 + j] = i.toString(16) + j.toString(16);
259 }
260 }
261
262 // Silverlight does not support spelling gray as grey.
263 var colorData = {
264 darkgrey: '#A9A9A9',
265 darkslategrey: '#2F4F4F',
266 dimgrey: '#696969',
267 grey: '#808080',
268 lightgrey: '#D3D3D3',
269 lightslategrey: '#778899',
270 slategrey: '#708090'
271 };
272
273
274 function getRgbHslContent(styleString) {
275 var start = styleString.indexOf('(', 3);
276 var end = styleString.indexOf(')', start + 1);
277 var parts = styleString.substring(start + 1, end).split(',');
278 // add alpha if needed
279 if (parts.length == 4 && styleString.substr(3, 1) == 'a') {
280 alpha = +parts[3];
281 } else {
282 parts[3] = 1;
283 }
284 return parts;
285 }
286
287 function percent(s) {
288 return parseFloat(s) / 100;
289 }
290
291 function clamp(v, min, max) {
292 return Math.min(max, Math.max(min, v));
293 }
294
295 function hslToRgb(parts){
296 var r, g, b;
297 h = parseFloat(parts[0]) / 360 % 360;
298 if (h < 0)
299 h++;
300 s = clamp(percent(parts[1]), 0, 1);
301 l = clamp(percent(parts[2]), 0, 1);
302 if (s == 0) {
303 r = g = b = l; // achromatic
304 } else {
305 var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
306 var p = 2 * l - q;
307 r = hueToRgb(p, q, h + 1 / 3);
308 g = hueToRgb(p, q, h);
309 b = hueToRgb(p, q, h - 1 / 3);
310 }
311
312 return decToHex[Math.floor(r * 255)] +
313 decToHex[Math.floor(g * 255)] +
314 decToHex[Math.floor(b * 255)];
315 }
316
317 function hueToRgb(m1, m2, h) {
318 if (h < 0)
319 h++;
320 if (h > 1)
321 h--;
322
323 if (6 * h < 1)
324 return m1 + (m2 - m1) * 6 * h;
325 else if (2 * h < 1)
326 return m2;
327 else if (3 * h < 2)
328 return m1 + (m2 - m1) * (2 / 3 - h) * 6;
329 else
330 return m1;
331 }
332
333 function translateColor(styleString) {
334 var str, alpha = 1;
335
336 styleString = String(styleString);
337 if (styleString.charAt(0) == '#') {
338 return styleString;
339 } else if (/^rgb/.test(styleString)) {
340 var parts = getRgbHslContent(styleString);
341 var str = '', n;
342 for (var i = 0; i < 3; i++) {
343 if (parts[i].indexOf('%') != -1) {
344 n = Math.floor(percent(parts[i]) * 255);
345 } else {
346 n = +parts[i];
347 }
348 str += decToHex[clamp(n, 0, 255)];
349 }
350 alpha = parts[3];
351 } else if (/^hsl/.test(styleString)) {
352 var parts = getRgbHslContent(styleString);
353 str = hslToRgb(parts);
354 alpha = parts[3];
355 } else if (styleString in colorData) {
356 return colorData[styleString];
357 } else {
358 return styleString;
359 }
360 return '#' + dec2hex[Math.floor(alpha * 255)] + str;
361 }
362
363 function processLineCap(lineCap) {
364 switch (lineCap) {
365 case 'butt':
366 return 'flat';
367 case 'round':
368 return 'round';
369 case 'square':
370 default:
371 return 'square';
372 }
373 }
374
375 function getRoot(ctx) {
376 return ctx.canvas.firstChild.firstChild.content.findName('root');
377 }
378
379 function create(ctx, s, opt_args) {
380 if (opt_args) {
381 s = s.replace(/\%(\d+)/g, function(match, index) {
382 return opt_args[+index - 1];
383 });
384 }
385
386 try {
387 return ctx.canvas.firstChild.firstChild.content.createFromXaml(s);
388 } catch (ex) {
389 throw Error('Could not create XAML from: ' + s);
390 }
391 }
392
393 function drawShape(ctx, s, opt_args) {
394 var canvas = ctx.lastCanvas_ || create(ctx, '<Canvas/>');
395 var shape = create(ctx, s, opt_args);
396 canvas.children.add(shape);
397 transformObject(ctx, canvas, ctx.m_);
398 if (!ctx.lastCanvas_) {
399 getRoot(ctx).children.add(canvas);
400 ctx.lastCanvas_ = canvas;
401 }
402 return shape;
403 }
404
405 function createBrushObject(ctx, value) {
406 if (value instanceof CanvasGradient_) {
407 return value.createBrush_(ctx);
408 } else if (value instanceof CanvasPattern_) {
409 throw Error('Not implemented');
410 } else {
411 return create(ctx, '<SolidColorBrush Color="%1"/>',
412 [translateColor(value)]);
413 }
414 }
415
416 /**
417 * This class implements CanvasRenderingContext2D interface as described by
418 * the WHATWG.
419 * @param {HTMLElement} surfaceElement The element that the 2D context should
420 * be associated with
421 */
422 function CanvasRenderingContext2D_(surfaceElement) {
423 this.m_ = createMatrixIdentity();
424 this.lastCanvas_ = null;
425
426 this.mStack_ = [];
427 this.aStack_ = [];
428 this.currentPath_ = [];
429
430 // Canvas context properties
431 this.strokeStyle = '#000';
432 this.fillStyle = '#000';
433
434 this.lineWidth = 1;
435 this.lineJoin = 'miter';
436 this.lineCap = 'butt';
437 this.miterLimit = 10;
438 this.globalAlpha = 1;
439 this.canvas = surfaceElement;
440 };
441
442
443 var contextPrototype = CanvasRenderingContext2D_.prototype;
444
445 contextPrototype.clearRect = function() {
446 var root = getRoot(this);
447 root.children.clear();
448
449 // TODO: Implement
450 this.currentPath_ = [];
451 this.lastCanvas_ = null;
452
453 };
454
455 contextPrototype.beginPath = function() {
456 // TODO: Branch current matrix so that save/restore has no effect
457 // as per safari docs.
458
459 this.currentPath_ = [];
460 };
461
462 contextPrototype.moveTo = function(aX, aY) {
463 this.currentPath_.push('M' + aX + ',' + aY);
464 };
465
466 contextPrototype.lineTo = function(aX, aY) {
467 if (this.currentPath_.length == 0) return;
468 this.currentPath_.push('L' + aX + ',' + aY);
469 };
470
471 contextPrototype.bezierCurveTo = function(aCP1x, aCP1y,
472 aCP2x, aCP2y,
473 aX, aY) {
474 if (this.currentPath_.length == 0) return;
475 this.currentPath_.push('C' + aCP1x + ',' + aCP1y + ' ' +
476 aCP2x + ',' + aCP2y + ' ' +
477 aX + ' ' + aY);
478 };
479
480 contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) {
481 if (this.currentPath_.length == 0) return;
482 this.currentPath_.push('Q' + aCPx + ',' + aCPy + ' ' +
483 aX + ',' + aY);
484 };
485
486 contextPrototype.arcTo = function(x1, y1, x2, y2, radius) {
487 if (this.currentPath_.length == 0) return;
488 // TODO: Implement
489 };
490
491 contextPrototype.arc = function(aX, aY, aRadius,
492 aStartAngle, aEndAngle, aClockwise) {
493 var deltaAngle = Math.abs(aStartAngle - aEndAngle);
494 // If start and stop are the same WebKit and Moz does nothing
495 if (aStartAngle == aEndAngle) {
496 // different browsers behave differently here so we do the easiest thing
497 return;
498 }
499
500 var endX = aX + aRadius * Math.cos(aEndAngle);
501 var endY = aY + aRadius * Math.sin(aEndAngle);
502
503 if (deltaAngle >= 2 * Math.PI) {
504 // if larger than 2PI
505 this.arc(aX, aY, aRadius, aStartAngle, aStartAngle + Math.PI, aClockwise);
506 this.arc(aX, aY, aRadius, aStartAngle + Math.PI,
507 aStartAngle + 2 * Math.PI, aClockwise);
508 // now move to end point
509 this.moveTo(endX, endY);
510 return;
511 }
512
513 var startX = aX + aRadius * Math.cos(aStartAngle);
514 var startY = aY + aRadius * Math.sin(aStartAngle);
515 var rotationAngle = deltaAngle * 180 / Math.PI; // sign, abs?
516 var sweepDirection = aClockwise ? 0 : 1;
517 var isLargeArc = rotationAngle >= 180 == Boolean(aClockwise) ? 0 : 1;
518
519 if (this.currentPath_.length != 0) {
520 // add line to start point
521 this.lineTo(startX, startY);
522 } else {
523 this.moveTo(startX, startY);
524 }
525
526 this.currentPath_.push('A' + aRadius + ',' + aRadius + ' ' +
527 rotationAngle + ' ' +
528 isLargeArc + ' ' +
529 sweepDirection + ' ' +
530 endX + ',' + endY);
531 };
532
533 contextPrototype.rect = function(aX, aY, aWidth, aHeight) {
534 this.moveTo(aX, aY);
535 this.lineTo(aX + aWidth, aY);
536 this.lineTo(aX + aWidth, aY + aHeight);
537 this.lineTo(aX, aY + aHeight);
538 this.closePath();
539 };
540
541 contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) {
542 // Will destroy any existing path (same as FF behaviour)
543 this.beginPath();
544 this.moveTo(aX, aY);
545 this.lineTo(aX + aWidth, aY);
546 this.lineTo(aX + aWidth, aY + aHeight);
547 this.lineTo(aX, aY + aHeight);
548 this.closePath();
549 this.stroke();
550 this.currentPath_ = [];
551 };
552
553 contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) {
554 // Will destroy any existing path (same as FF behaviour)
555 this.beginPath();
556 this.moveTo(aX, aY);
557 this.lineTo(aX + aWidth, aY);
558 this.lineTo(aX + aWidth, aY + aHeight);
559 this.lineTo(aX, aY + aHeight);
560 this.closePath();
561 this.fill();
562 this.currentPath_ = [];
563 };
564
565 contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) {
566 return new LinearCanvasGradient_(aX0, aY0, aX1, aY1);
567 };
568
569 contextPrototype.createRadialGradient = function(x0, y0,
570 r0, x1,
571 y1, r1) {
572 return new RadialCanvasGradient_(x0, y0, r0, x1, y1, r1);
573 };
574
575 contextPrototype.drawImage = function (image, var_args) {
576 var dx, dy, dw, dh, sx, sy, sw, sh;
577
578 // For Silverlight we don't need to get the size of the image since
579 // Silverlight uses the image original dimension if not provided.
580
581 if (arguments.length == 3) {
582 dx = arguments[1];
583 dy = arguments[2];
584 // Keep sx, sy, sw, dw, sh and dh undefined
585 } else if (arguments.length == 5) {
586 dx = arguments[1];
587 dy = arguments[2];
588 dw = arguments[3];
589 dh = arguments[4];
590 // Keep sx, sy, sw and sh undefined
591 } else if (arguments.length == 9) {
592 sx = arguments[1];
593 sy = arguments[2];
594 sw = arguments[3];
595 sh = arguments[4];
596 dx = arguments[5];
597 dy = arguments[6];
598 dw = arguments[7];
599 dh = arguments[8];
600 } else {
601 throw Error('Invalid number of arguments');
602 }
603
604 var slImage;
605
606 // If we have a source rect we need to clip the image.
607 if (arguments.length == 9) {
608 slImage = drawShape(this, '<Image Source="%1"/>', [image.src]);
609
610 var clipRect = create(this,
611 '<RectangleGeometry Rect="%1,%2,%3,%4"/>', [sx, sy, sw, sh]);
612 slImage.clip = clipRect;
613
614 var m = createMatrixIdentity();
615
616 // translate to 0,0
617 m[2][0] = -sx;
618 m[2][1] = -sy;
619
620 // scale
621 var m2 = createMatrixIdentity();
622 m2[0][0] = dw / sw;
623 m2[1][1] = dh / sh;
624
625 m = matrixMultiply(m, m2);
626
627 // translate to destination
628 m[2][0] += dx;
629 m[2][1] += dy;
630
631 transformObject(this, slImage, m);
632
633 } else {
634 slImage = drawShape(this,
635 '<Image Source="%1" Canvas.Left="%2" Canvas.Top="%3"/>',
636 [image.src, dx, dy]);
637 if (dw != undefined || dh != undefined) {
638 slImage.width = dw;
639 slImage.height = dh;
640 slImage.stretch = 'fill';
641 }
642 }
643 };
644
645 contextPrototype.stroke = function() {
646 if (this.currentPath_.length == 0) return;
647 var path = drawShape(this, '<Path Data="%1"/>',
648 [this.currentPath_.join(' ')]);
649 path.stroke = createBrushObject(this, this.strokeStyle);
650 path.opacity = this.globalAlpha;
651 path.strokeThickness = this.lineWidth;
652 path.strokeMiterLimit = this.miterLimit;
653 path.strokeLineJoin = this.lineJoin;
654 // Canvas does not differentiate start from end
655 path.strokeEndLineCap = path.strokeStartLineCap =
656 processLineCap(this.lineCap);
657 };
658
659 contextPrototype.fill = function() {
660 if (this.currentPath_.length == 0) return;
661 var path = drawShape(this, '<Path Data="%1"/>',
662 [this.currentPath_.join(' ')]);
663 // The spec says to use non zero but Silverlight uses EvenOdd by defaul
664 path.data.fillRule = 'NonZero';
665 path.fill = createBrushObject(this, this.fillStyle);
666 path.fill.opacity = this.globalAlpha;
667 // TODO: What about even-odd etc?
668 };
669
670 contextPrototype.closePath = function() {
671 this.currentPath_.push('z');
672 };
673
674 /**
675 * Sets the transformation matrix and marks things as dirty
676 */
677 function setM(self, m) {
678 self.m_ = m;
679 self.lastCanvas_ = null;
680 };
681
682 contextPrototype.save = function() {
683 var o = {};
684 copyState(this, o);
685 this.aStack_.push(o);
686 this.mStack_.push(this.m_);
687 setM(this, matrixMultiply(createMatrixIdentity(), this.m_));
688 };
689
690 contextPrototype.restore = function() {
691 if (this.aStack_.length) {
692 copyState(this.aStack_.pop(), this);
693 this.m_ = this.mStack_.pop();
694 }
695 };
696
697 contextPrototype.translate = function(aX, aY) {
698 var m1 = [
699 [1, 0, 0],
700 [0, 1, 0],
701 [aX, aY, 1]
702 ];
703
704 setM(this, matrixMultiply(m1, this.m_));
705 };
706
707 contextPrototype.rotate = function(aRot) {
708 var c = Math.cos(aRot);
709 var s = Math.sin(aRot);
710
711 var m1 = [
712 [c, s, 0],
713 [-s, c, 0],
714 [0, 0, 1]
715 ];
716
717 setM(this, matrixMultiply(m1, this.m_));
718 };
719
720 contextPrototype.scale = function(aX, aY) {
721 var m1 = [
722 [aX, 0, 0],
723 [0, aY, 0],
724 [0, 0, 1]
725 ];
726
727 setM(this, matrixMultiply(m1, this.m_));
728 };
729
730 contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) {
731 var m1 = [
732 [m11, m12, 0],
733 [m21, m22, 0],
734 [ dx, dy, 1]
735 ];
736
737 setM(this, matrixMultiply(m1, this.m_));
738 };
739
740 contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) {
741 setM(this, [
742 [m11, m12, 0],
743 [m21, m22, 0],
744 [ dx, dy, 1],
745 ]);
746 };
747
748 contextPrototype.clip = function() {
749 if (this.currentPath_.length) {
750 var clip = this.currentPath_.join(' ');
751 var canvas = create(this, '<Canvas Width="%1" Height="%2" Clip="%3"/>',
752 [getRoot(this).width, getRoot(this).height, clip]);
753 var parent = this.lastCanvas_ || getRoot(this);
754
755 parent.children.add(canvas);
756 this.lastCanvas_ = canvas;
757 }
758 };
759
760 contextPrototype.createPattern = function() {
761 return new CanvasPattern_;
762 };
763
764 // Gradient / Pattern Stubs
765 function CanvasGradient_() {
766 this.colors_ = [];
767 }
768
769 CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) {
770 aColor = translateColor(aColor);
771 this.colors_.push({offset: aOffset, color: aColor});
772 };
773
774 CanvasGradient_.prototype.createStops_ = function(ctx, brushObj, colors) {
775 var gradientStopCollection = brushObj.gradientStops;
776 for (var i = 0, c; c = colors[i]; i++) {
777 var color = translateColor(c.color);
778 gradientStopCollection.add(create(ctx,
779 '<GradientStop Color="%1" Offset="%2"/>', [color, c.offset]));
780 }
781 };
782
783 function LinearCanvasGradient_(x0, y0, x1, y1) {
784 CanvasGradient_.call(this);
785 this.x0_ = x0;
786 this.y0_ = y0;
787 this.x1_ = x1;
788 this.y1_ = y1;
789 }
790 LinearCanvasGradient_.prototype = new CanvasGradient_;
791
792 LinearCanvasGradient_.prototype.createBrush_ = function(ctx) {
793 var brushObj = create(ctx, '<LinearGradientBrush MappingMode="Absolute" ' +
794 'StartPoint="%1,%2" EndPoint="%3,%4"/>',
795 [this.x0_, this.y0_, this.x1_, this.y1_]);
796 this.createStops_(ctx, brushObj, this.colors_);
797 return brushObj;
798 };
799
800 function isNanOrInfinite(v) {
801 return isNaN(v) || !isFinite(v);
802 }
803
804 function RadialCanvasGradient_(x0, y0, r0, x1, y1, r1) {
805 if (r0 < 0 || r1 < 0 || isNanOrInfinite(x0) || isNanOrInfinite(y0) ||
806 isNanOrInfinite(x1) || isNanOrInfinite(y1)) {
807 // IE does not support DOMException so this is as close as we get.
808 var error = Error('DOMException.INDEX_SIZE_ERR');
809 error.code = 1;
810 throw error;
811 }
812
813 CanvasGradient_.call(this);
814 this.x0_ = x0;
815 this.y0_ = y0;
816 this.r0_ = r0;
817 this.x1_ = x1;
818 this.y1_ = y1;
819 this.r1_ = r1;
820 }
821 RadialCanvasGradient_.prototype = new CanvasGradient_;
822
823 CanvasGradient_.prototype.createBrush_ = function(ctx) {
824 if (this.x0_ == this.x1_ && this.y0_ == this.y1_ && this.r0_ == this.r1_) {
825 return null;
826 }
827
828 var radius = Math.max(this.r0_, this.r1_);
829 var minRadius = Math.min(this.r0_, this.r1_);
830 var brushObj = create(ctx, '<RadialGradientBrush MappingMode="Absolute" ' +
831 'GradientOrigin="%1,%2" Center="%3,%4" ' +
832 'RadiusX="%5" RadiusY="%5"/>',
833 [this.x0_, this.y0_, this.x1_, this.y1_, radius]);
834
835 var colors = this.colors_.concat();
836
837 if (this.r1_ < this.r0_) {
838 // reverse color stop array
839 colors.reverse();
840 for (var i = 0, c; c = colors[i]; i++) {
841 c.offset = 1 - c.offset;
842 }
843 }
844
845 // sort the color stops
846 colors.sort(function(c1, c2) {
847 return c1.offset - c2.offset;
848 });
849
850 if (minRadius > 0) {
851 // We need to adjust the color stops since SL always have the inner radius
852 // at (0, 0) so we change the stops in case the min radius is not 0.
853 for (var i = 0, c; c = colors[i]; i++) {
854 c.offset = minRadius / radius + (radius - minRadius) / radius * c.offset;
855 }
856 }
857
858 this.createStops_(ctx, brushObj, colors);
859 return brushObj;
860 };
861
862 function CanvasPattern_() {}
863
864 // set up externs
865 G_vmlCanvasManager = G_vmlCanvasManager_;
866 CanvasRenderingContext2D = CanvasRenderingContext2D_;
867 CanvasGradient = CanvasGradient_;
868 CanvasPattern = CanvasPattern_;
869
870 })();
871
872 } // if