excanvas.js 40 KB

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