excanvas.js 41 KB

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