PHP/JavaScript webapp to analyse spending habits
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

excanvas.js 41KB

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