/src/example/excanvas.js

http://jsgauge.googlecode.com/ · JavaScript · 1416 lines · 1326 code · 25 blank · 65 comment · 22 complexity · c466e683cc30546ee3f295829a0c009d MD5 · raw file

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