excanvas.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  1. //Filament Group modification note:
  2. //This version of excanvas is modified to support lazy loading of this file. More info here: http://pipwerks.com/2009/03/12/lazy-loading-excanvasjs/
  3. // Copyright 2006 Google Inc.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. // Known Issues:
  17. //
  18. // * Patterns are not implemented.
  19. // * Radial gradient are not implemented. The VML version of these look very
  20. // different from the canvas one.
  21. // * Clipping paths are not implemented.
  22. // * Coordsize. The width and height attribute have higher priority than the
  23. // width and height style values which isn't correct.
  24. // * Painting mode isn't implemented.
  25. // * Canvas width/height should is using content-box by default. IE in
  26. // Quirks mode will draw the canvas using border-box. Either change your
  27. // doctype to HTML5
  28. // (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype)
  29. // or use Box Sizing Behavior from WebFX
  30. // (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html)
  31. // * Non uniform scaling does not correctly scale strokes.
  32. // * Optimize. There is always room for speed improvements.
  33. // Only add this code if we do not already have a canvas implementation
  34. if (!document.createElement('canvas').getContext) {
  35. (function() {
  36. // alias some functions to make (compiled) code shorter
  37. var m = Math;
  38. var mr = m.round;
  39. var ms = m.sin;
  40. var mc = m.cos;
  41. var abs = m.abs;
  42. var sqrt = m.sqrt;
  43. // this is used for sub pixel precision
  44. var Z = 10;
  45. var Z2 = Z / 2;
  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. var G_vmlCanvasManager_ = {
  79. init: function(opt_doc) {
  80. if (/MSIE/.test(navigator.userAgent) && !window.opera) {
  81. var doc = opt_doc || document;
  82. // Create a dummy element so that IE will allow canvas elements to be
  83. // recognized.
  84. doc.createElement('canvas');
  85. if(doc.readyState !== "complete"){
  86. doc.attachEvent('onreadystatechange', bind(this.init_, this, doc));
  87. } else {
  88. this.init_(doc);
  89. }
  90. }
  91. },
  92. init_: function(doc) {
  93. // create xmlns
  94. if (!doc.namespaces['g_vml_']) {
  95. doc.namespaces.add('g_vml_', 'urn:schemas-microsoft-com:vml',
  96. '#default#VML');
  97. }
  98. if (!doc.namespaces['g_o_']) {
  99. doc.namespaces.add('g_o_', 'urn:schemas-microsoft-com:office:office',
  100. '#default#VML');
  101. }
  102. // Setup default CSS. Only add one style sheet per document
  103. if (!doc.styleSheets['ex_canvas_']) {
  104. var ss = doc.createStyleSheet();
  105. ss.owningElement.id = 'ex_canvas_';
  106. ss.cssText = 'canvas{display:inline-block;overflow:hidden;' +
  107. // default size is 300x150 in Gecko and Opera
  108. 'text-align:left;width:300px;height:150px}' +
  109. 'g_vml_\\:*{behavior:url(#default#VML)}' +
  110. 'g_o_\\:*{behavior:url(#default#VML)}';
  111. }
  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. // Remove fallback content. There is no way to hide text nodes so we
  130. // just remove all childNodes. We could hide all elements and remove
  131. // text nodes but who really cares about the fallback content.
  132. el.innerHTML = '';
  133. // do not use inline function because that will leak memory
  134. el.attachEvent('onpropertychange', onPropertyChange);
  135. el.attachEvent('onresize', onResize);
  136. var attrs = el.attributes;
  137. if (attrs.width && attrs.width.specified) {
  138. // TODO: use runtimeStyle and coordsize
  139. // el.getContext().setWidth_(attrs.width.nodeValue);
  140. el.style.width = attrs.width.nodeValue + 'px';
  141. } else {
  142. el.width = el.clientWidth;
  143. }
  144. if (attrs.height && attrs.height.specified) {
  145. // TODO: use runtimeStyle and coordsize
  146. // el.getContext().setHeight_(attrs.height.nodeValue);
  147. el.style.height = attrs.height.nodeValue + 'px';
  148. } else {
  149. el.height = el.clientHeight;
  150. }
  151. //el.getContext().setCoordsize_()
  152. }
  153. return el;
  154. }
  155. };
  156. function onPropertyChange(e) {
  157. var el = e.srcElement;
  158. switch (e.propertyName) {
  159. case 'width':
  160. el.style.width = el.attributes.width.nodeValue + 'px';
  161. el.getContext().clearRect();
  162. break;
  163. case 'height':
  164. el.style.height = el.attributes.height.nodeValue + 'px';
  165. el.getContext().clearRect();
  166. break;
  167. }
  168. }
  169. function onResize(e) {
  170. var el = e.srcElement;
  171. if (el.firstChild) {
  172. el.firstChild.style.width = el.clientWidth + 'px';
  173. el.firstChild.style.height = el.clientHeight + 'px';
  174. }
  175. }
  176. G_vmlCanvasManager_.init();
  177. // precompute "00" to "FF"
  178. var dec2hex = [];
  179. for (var i = 0; i < 16; i++) {
  180. for (var j = 0; j < 16; j++) {
  181. dec2hex[i * 16 + j] = i.toString(16) + j.toString(16);
  182. }
  183. }
  184. function createMatrixIdentity() {
  185. return [
  186. [1, 0, 0],
  187. [0, 1, 0],
  188. [0, 0, 1]
  189. ];
  190. }
  191. function matrixMultiply(m1, m2) {
  192. var result = createMatrixIdentity();
  193. for (var x = 0; x < 3; x++) {
  194. for (var y = 0; y < 3; y++) {
  195. var sum = 0;
  196. for (var z = 0; z < 3; z++) {
  197. sum += m1[x][z] * m2[z][y];
  198. }
  199. result[x][y] = sum;
  200. }
  201. }
  202. return result;
  203. }
  204. function copyState(o1, o2) {
  205. o2.fillStyle = o1.fillStyle;
  206. o2.lineCap = o1.lineCap;
  207. o2.lineJoin = o1.lineJoin;
  208. o2.lineWidth = o1.lineWidth;
  209. o2.miterLimit = o1.miterLimit;
  210. o2.shadowBlur = o1.shadowBlur;
  211. o2.shadowColor = o1.shadowColor;
  212. o2.shadowOffsetX = o1.shadowOffsetX;
  213. o2.shadowOffsetY = o1.shadowOffsetY;
  214. o2.strokeStyle = o1.strokeStyle;
  215. o2.globalAlpha = o1.globalAlpha;
  216. o2.arcScaleX_ = o1.arcScaleX_;
  217. o2.arcScaleY_ = o1.arcScaleY_;
  218. o2.lineScale_ = o1.lineScale_;
  219. }
  220. function processStyle(styleString) {
  221. var str, alpha = 1;
  222. styleString = String(styleString);
  223. if (styleString.substring(0, 3) == 'rgb') {
  224. var start = styleString.indexOf('(', 3);
  225. var end = styleString.indexOf(')', start + 1);
  226. var guts = styleString.substring(start + 1, end).split(',');
  227. str = '#';
  228. for (var i = 0; i < 3; i++) {
  229. str += dec2hex[Number(guts[i])];
  230. }
  231. if (guts.length == 4 && styleString.substr(3, 1) == 'a') {
  232. alpha = guts[3];
  233. }
  234. } else {
  235. str = styleString;
  236. }
  237. return {color: str, alpha: alpha};
  238. }
  239. function processLineCap(lineCap) {
  240. switch (lineCap) {
  241. case 'butt':
  242. return 'flat';
  243. case 'round':
  244. return 'round';
  245. case 'square':
  246. default:
  247. return 'square';
  248. }
  249. }
  250. /**
  251. * This class implements CanvasRenderingContext2D interface as described by
  252. * the WHATWG.
  253. * @param {HTMLElement} surfaceElement The element that the 2D context should
  254. * be associated with
  255. */
  256. function CanvasRenderingContext2D_(surfaceElement) {
  257. this.m_ = createMatrixIdentity();
  258. this.mStack_ = [];
  259. this.aStack_ = [];
  260. this.currentPath_ = [];
  261. // Canvas context properties
  262. this.strokeStyle = '#000';
  263. this.fillStyle = '#000';
  264. this.lineWidth = 1;
  265. this.lineJoin = 'miter';
  266. this.lineCap = 'butt';
  267. this.miterLimit = Z * 1;
  268. this.globalAlpha = 1;
  269. this.canvas = surfaceElement;
  270. var el = surfaceElement.ownerDocument.createElement('div');
  271. el.style.width = surfaceElement.clientWidth + 'px';
  272. el.style.height = surfaceElement.clientHeight + 'px';
  273. el.style.overflow = 'hidden';
  274. el.style.position = 'absolute';
  275. surfaceElement.appendChild(el);
  276. this.element_ = el;
  277. this.arcScaleX_ = 1;
  278. this.arcScaleY_ = 1;
  279. this.lineScale_ = 1;
  280. }
  281. var contextPrototype = CanvasRenderingContext2D_.prototype;
  282. contextPrototype.clearRect = function() {
  283. this.element_.innerHTML = '';
  284. };
  285. contextPrototype.beginPath = function() {
  286. // TODO: Branch current matrix so that save/restore has no effect
  287. // as per safari docs.
  288. this.currentPath_ = [];
  289. };
  290. contextPrototype.moveTo = function(aX, aY) {
  291. var p = this.getCoords_(aX, aY);
  292. this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y});
  293. this.currentX_ = p.x;
  294. this.currentY_ = p.y;
  295. };
  296. contextPrototype.lineTo = function(aX, aY) {
  297. var p = this.getCoords_(aX, aY);
  298. this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y});
  299. this.currentX_ = p.x;
  300. this.currentY_ = p.y;
  301. };
  302. contextPrototype.bezierCurveTo = function(aCP1x, aCP1y,
  303. aCP2x, aCP2y,
  304. aX, aY) {
  305. var p = this.getCoords_(aX, aY);
  306. var cp1 = this.getCoords_(aCP1x, aCP1y);
  307. var cp2 = this.getCoords_(aCP2x, aCP2y);
  308. bezierCurveTo(this, cp1, cp2, p);
  309. };
  310. // Helper function that takes the already fixed cordinates.
  311. function bezierCurveTo(self, cp1, cp2, p) {
  312. self.currentPath_.push({
  313. type: 'bezierCurveTo',
  314. cp1x: cp1.x,
  315. cp1y: cp1.y,
  316. cp2x: cp2.x,
  317. cp2y: cp2.y,
  318. x: p.x,
  319. y: p.y
  320. });
  321. self.currentX_ = p.x;
  322. self.currentY_ = p.y;
  323. }
  324. contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) {
  325. // the following is lifted almost directly from
  326. // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes
  327. var cp = this.getCoords_(aCPx, aCPy);
  328. var p = this.getCoords_(aX, aY);
  329. var cp1 = {
  330. x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_),
  331. y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_)
  332. };
  333. var cp2 = {
  334. x: cp1.x + (p.x - this.currentX_) / 3.0,
  335. y: cp1.y + (p.y - this.currentY_) / 3.0
  336. };
  337. bezierCurveTo(this, cp1, cp2, p);
  338. };
  339. contextPrototype.arc = function(aX, aY, aRadius,
  340. aStartAngle, aEndAngle, aClockwise) {
  341. aRadius *= Z;
  342. var arcType = aClockwise ? 'at' : 'wa';
  343. var xStart = aX + mc(aStartAngle) * aRadius - Z2;
  344. var yStart = aY + ms(aStartAngle) * aRadius - Z2;
  345. var xEnd = aX + mc(aEndAngle) * aRadius - Z2;
  346. var yEnd = aY + ms(aEndAngle) * aRadius - Z2;
  347. // IE won't render arches drawn counter clockwise if xStart == xEnd.
  348. if (xStart == xEnd && !aClockwise) {
  349. xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something
  350. // that can be represented in binary
  351. }
  352. var p = this.getCoords_(aX, aY);
  353. var pStart = this.getCoords_(xStart, yStart);
  354. var pEnd = this.getCoords_(xEnd, yEnd);
  355. this.currentPath_.push({type: arcType,
  356. x: p.x,
  357. y: p.y,
  358. radius: aRadius,
  359. xStart: pStart.x,
  360. yStart: pStart.y,
  361. xEnd: pEnd.x,
  362. yEnd: pEnd.y});
  363. };
  364. contextPrototype.rect = function(aX, aY, aWidth, aHeight) {
  365. this.moveTo(aX, aY);
  366. this.lineTo(aX + aWidth, aY);
  367. this.lineTo(aX + aWidth, aY + aHeight);
  368. this.lineTo(aX, aY + aHeight);
  369. this.closePath();
  370. };
  371. contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) {
  372. var oldPath = this.currentPath_;
  373. this.beginPath();
  374. this.moveTo(aX, aY);
  375. this.lineTo(aX + aWidth, aY);
  376. this.lineTo(aX + aWidth, aY + aHeight);
  377. this.lineTo(aX, aY + aHeight);
  378. this.closePath();
  379. this.stroke();
  380. this.currentPath_ = oldPath;
  381. };
  382. contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) {
  383. var oldPath = this.currentPath_;
  384. this.beginPath();
  385. this.moveTo(aX, aY);
  386. this.lineTo(aX + aWidth, aY);
  387. this.lineTo(aX + aWidth, aY + aHeight);
  388. this.lineTo(aX, aY + aHeight);
  389. this.closePath();
  390. this.fill();
  391. this.currentPath_ = oldPath;
  392. };
  393. contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) {
  394. var gradient = new CanvasGradient_('gradient');
  395. gradient.x0_ = aX0;
  396. gradient.y0_ = aY0;
  397. gradient.x1_ = aX1;
  398. gradient.y1_ = aY1;
  399. return gradient;
  400. };
  401. contextPrototype.createRadialGradient = function(aX0, aY0, aR0,
  402. aX1, aY1, aR1) {
  403. var gradient = new CanvasGradient_('gradientradial');
  404. gradient.x0_ = aX0;
  405. gradient.y0_ = aY0;
  406. gradient.r0_ = aR0;
  407. gradient.x1_ = aX1;
  408. gradient.y1_ = aY1;
  409. gradient.r1_ = aR1;
  410. return gradient;
  411. };
  412. contextPrototype.drawImage = function(image, var_args) {
  413. var dx, dy, dw, dh, sx, sy, sw, sh;
  414. // to find the original width we overide the width and height
  415. var oldRuntimeWidth = image.runtimeStyle.width;
  416. var oldRuntimeHeight = image.runtimeStyle.height;
  417. image.runtimeStyle.width = 'auto';
  418. image.runtimeStyle.height = 'auto';
  419. // get the original size
  420. var w = image.width;
  421. var h = image.height;
  422. // and remove overides
  423. image.runtimeStyle.width = oldRuntimeWidth;
  424. image.runtimeStyle.height = oldRuntimeHeight;
  425. if (arguments.length == 3) {
  426. dx = arguments[1];
  427. dy = arguments[2];
  428. sx = sy = 0;
  429. sw = dw = w;
  430. sh = dh = h;
  431. } else if (arguments.length == 5) {
  432. dx = arguments[1];
  433. dy = arguments[2];
  434. dw = arguments[3];
  435. dh = arguments[4];
  436. sx = sy = 0;
  437. sw = w;
  438. sh = h;
  439. } else if (arguments.length == 9) {
  440. sx = arguments[1];
  441. sy = arguments[2];
  442. sw = arguments[3];
  443. sh = arguments[4];
  444. dx = arguments[5];
  445. dy = arguments[6];
  446. dw = arguments[7];
  447. dh = arguments[8];
  448. } else {
  449. throw Error('Invalid number of arguments');
  450. }
  451. var d = this.getCoords_(dx, dy);
  452. var w2 = sw / 2;
  453. var h2 = sh / 2;
  454. var vmlStr = [];
  455. var W = 10;
  456. var H = 10;
  457. // For some reason that I've now forgotten, using divs didn't work
  458. vmlStr.push(' <g_vml_:group',
  459. ' coordsize="', Z * W, ',', Z * H, '"',
  460. ' coordorigin="0,0"' ,
  461. ' style="width:', W, 'px;height:', H, 'px;position:absolute;');
  462. // If filters are necessary (rotation exists), create them
  463. // filters are bog-slow, so only create them if abbsolutely necessary
  464. // The following check doesn't account for skews (which don't exist
  465. // in the canvas spec (yet) anyway.
  466. if (this.m_[0][0] != 1 || this.m_[0][1]) {
  467. var filter = [];
  468. // Note the 12/21 reversal
  469. filter.push('M11=', this.m_[0][0], ',',
  470. 'M12=', this.m_[1][0], ',',
  471. 'M21=', this.m_[0][1], ',',
  472. 'M22=', this.m_[1][1], ',',
  473. 'Dx=', mr(d.x / Z), ',',
  474. 'Dy=', mr(d.y / Z), '');
  475. // Bounding box calculation (need to minimize displayed area so that
  476. // filters don't waste time on unused pixels.
  477. var max = d;
  478. var c2 = this.getCoords_(dx + dw, dy);
  479. var c3 = this.getCoords_(dx, dy + dh);
  480. var c4 = this.getCoords_(dx + dw, dy + dh);
  481. max.x = m.max(max.x, c2.x, c3.x, c4.x);
  482. max.y = m.max(max.y, c2.y, c3.y, c4.y);
  483. vmlStr.push('padding:0 ', mr(max.x / Z), 'px ', mr(max.y / Z),
  484. 'px 0;filter:progid:DXImageTransform.Microsoft.Matrix(',
  485. filter.join(''), ", sizingmethod='clip');")
  486. } else {
  487. vmlStr.push('top:', mr(d.y / Z), 'px;left:', mr(d.x / Z), 'px;');
  488. }
  489. vmlStr.push(' ">' ,
  490. '<g_vml_:image src="', image.src, '"',
  491. ' style="width:', Z * dw, 'px;',
  492. ' height:', Z * dh, 'px;"',
  493. ' cropleft="', sx / w, '"',
  494. ' croptop="', sy / h, '"',
  495. ' cropright="', (w - sx - sw) / w, '"',
  496. ' cropbottom="', (h - sy - sh) / h, '"',
  497. ' />',
  498. '</g_vml_:group>');
  499. this.element_.insertAdjacentHTML('BeforeEnd',
  500. vmlStr.join(''));
  501. };
  502. contextPrototype.stroke = function(aFill) {
  503. var lineStr = [];
  504. var lineOpen = false;
  505. var a = processStyle(aFill ? this.fillStyle : this.strokeStyle);
  506. var color = a.color;
  507. var opacity = a.alpha * this.globalAlpha;
  508. var W = 10;
  509. var H = 10;
  510. lineStr.push('<g_vml_:shape',
  511. ' filled="', !!aFill, '"',
  512. ' style="position:absolute;width:', W, 'px;height:', H, 'px;"',
  513. ' coordorigin="0 0" coordsize="', Z * W, ' ', Z * H, '"',
  514. ' stroked="', !aFill, '"',
  515. ' path="');
  516. var newSeq = false;
  517. var min = {x: null, y: null};
  518. var max = {x: null, y: null};
  519. for (var i = 0; i < this.currentPath_.length; i++) {
  520. var p = this.currentPath_[i];
  521. var c;
  522. switch (p.type) {
  523. case 'moveTo':
  524. c = p;
  525. lineStr.push(' m ', mr(p.x), ',', mr(p.y));
  526. break;
  527. case 'lineTo':
  528. lineStr.push(' l ', mr(p.x), ',', mr(p.y));
  529. break;
  530. case 'close':
  531. lineStr.push(' x ');
  532. p = null;
  533. break;
  534. case 'bezierCurveTo':
  535. lineStr.push(' c ',
  536. mr(p.cp1x), ',', mr(p.cp1y), ',',
  537. mr(p.cp2x), ',', mr(p.cp2y), ',',
  538. mr(p.x), ',', mr(p.y));
  539. break;
  540. case 'at':
  541. case 'wa':
  542. lineStr.push(' ', p.type, ' ',
  543. mr(p.x - this.arcScaleX_ * p.radius), ',',
  544. mr(p.y - this.arcScaleY_ * p.radius), ' ',
  545. mr(p.x + this.arcScaleX_ * p.radius), ',',
  546. mr(p.y + this.arcScaleY_ * p.radius), ' ',
  547. mr(p.xStart), ',', mr(p.yStart), ' ',
  548. mr(p.xEnd), ',', mr(p.yEnd));
  549. break;
  550. }
  551. // TODO: Following is broken for curves due to
  552. // move to proper paths.
  553. // Figure out dimensions so we can do gradient fills
  554. // properly
  555. if (p) {
  556. if (min.x == null || p.x < min.x) {
  557. min.x = p.x;
  558. }
  559. if (max.x == null || p.x > max.x) {
  560. max.x = p.x;
  561. }
  562. if (min.y == null || p.y < min.y) {
  563. min.y = p.y;
  564. }
  565. if (max.y == null || p.y > max.y) {
  566. max.y = p.y;
  567. }
  568. }
  569. }
  570. lineStr.push(' ">');
  571. if (!aFill) {
  572. var lineWidth = this.lineScale_ * this.lineWidth;
  573. // VML cannot correctly render a line if the width is less than 1px.
  574. // In that case, we dilute the color to make the line look thinner.
  575. if (lineWidth < 1) {
  576. opacity *= lineWidth;
  577. }
  578. lineStr.push(
  579. '<g_vml_:stroke',
  580. ' opacity="', opacity, '"',
  581. ' joinstyle="', this.lineJoin, '"',
  582. ' miterlimit="', this.miterLimit, '"',
  583. ' endcap="', processLineCap(this.lineCap), '"',
  584. ' weight="', lineWidth, 'px"',
  585. ' color="', color, '" />'
  586. );
  587. } else if (typeof this.fillStyle == 'object') {
  588. var fillStyle = this.fillStyle;
  589. var angle = 0;
  590. var focus = {x: 0, y: 0};
  591. // additional offset
  592. var shift = 0;
  593. // scale factor for offset
  594. var expansion = 1;
  595. if (fillStyle.type_ == 'gradient') {
  596. var x0 = fillStyle.x0_ / this.arcScaleX_;
  597. var y0 = fillStyle.y0_ / this.arcScaleY_;
  598. var x1 = fillStyle.x1_ / this.arcScaleX_;
  599. var y1 = fillStyle.y1_ / this.arcScaleY_;
  600. var p0 = this.getCoords_(x0, y0);
  601. var p1 = this.getCoords_(x1, y1);
  602. var dx = p1.x - p0.x;
  603. var dy = p1.y - p0.y;
  604. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  605. // The angle should be a non-negative number.
  606. if (angle < 0) {
  607. angle += 360;
  608. }
  609. // Very small angles produce an unexpected result because they are
  610. // converted to a scientific notation string.
  611. if (angle < 1e-6) {
  612. angle = 0;
  613. }
  614. } else {
  615. var p0 = this.getCoords_(fillStyle.x0_, fillStyle.y0_);
  616. var width = max.x - min.x;
  617. var height = max.y - min.y;
  618. focus = {
  619. x: (p0.x - min.x) / width,
  620. y: (p0.y - min.y) / height
  621. };
  622. width /= this.arcScaleX_ * Z;
  623. height /= this.arcScaleY_ * Z;
  624. var dimension = m.max(width, height);
  625. shift = 2 * fillStyle.r0_ / dimension;
  626. expansion = 2 * fillStyle.r1_ / dimension - shift;
  627. }
  628. // We need to sort the color stops in ascending order by offset,
  629. // otherwise IE won't interpret it correctly.
  630. var stops = fillStyle.colors_;
  631. stops.sort(function(cs1, cs2) {
  632. return cs1.offset - cs2.offset;
  633. });
  634. var length = stops.length;
  635. var color1 = stops[0].color;
  636. var color2 = stops[length - 1].color;
  637. var opacity1 = stops[0].alpha * this.globalAlpha;
  638. var opacity2 = stops[length - 1].alpha * this.globalAlpha;
  639. var colors = [];
  640. for (var i = 0; i < length; i++) {
  641. var stop = stops[i];
  642. colors.push(stop.offset * expansion + shift + ' ' + stop.color);
  643. }
  644. // When colors attribute is used, the meanings of opacity and o:opacity2
  645. // are reversed.
  646. lineStr.push('<g_vml_:fill type="', fillStyle.type_, '"',
  647. ' method="none" focus="100%"',
  648. ' color="', color1, '"',
  649. ' color2="', color2, '"',
  650. ' colors="', colors.join(','), '"',
  651. ' opacity="', opacity2, '"',
  652. ' g_o_:opacity2="', opacity1, '"',
  653. ' angle="', angle, '"',
  654. ' focusposition="', focus.x, ',', focus.y, '" />');
  655. } else {
  656. lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity,
  657. '" />');
  658. }
  659. lineStr.push('</g_vml_:shape>');
  660. this.element_.insertAdjacentHTML('beforeEnd', lineStr.join(''));
  661. };
  662. contextPrototype.fill = function() {
  663. this.stroke(true);
  664. }
  665. contextPrototype.closePath = function() {
  666. this.currentPath_.push({type: 'close'});
  667. };
  668. /**
  669. * @private
  670. */
  671. contextPrototype.getCoords_ = function(aX, aY) {
  672. var m = this.m_;
  673. return {
  674. x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2,
  675. y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2
  676. }
  677. };
  678. contextPrototype.save = function() {
  679. var o = {};
  680. copyState(this, o);
  681. this.aStack_.push(o);
  682. this.mStack_.push(this.m_);
  683. this.m_ = matrixMultiply(createMatrixIdentity(), this.m_);
  684. };
  685. contextPrototype.restore = function() {
  686. copyState(this.aStack_.pop(), this);
  687. this.m_ = this.mStack_.pop();
  688. };
  689. function matrixIsFinite(m) {
  690. for (var j = 0; j < 3; j++) {
  691. for (var k = 0; k < 2; k++) {
  692. if (!isFinite(m[j][k]) || isNaN(m[j][k])) {
  693. return false;
  694. }
  695. }
  696. }
  697. return true;
  698. }
  699. function setM(ctx, m, updateLineScale) {
  700. if (!matrixIsFinite(m)) {
  701. return;
  702. }
  703. ctx.m_ = m;
  704. if (updateLineScale) {
  705. // Get the line scale.
  706. // Determinant of this.m_ means how much the area is enlarged by the
  707. // transformation. So its square root can be used as a scale factor
  708. // for width.
  709. var det = m[0][0] * m[1][1] - m[0][1] * m[1][0];
  710. ctx.lineScale_ = sqrt(abs(det));
  711. }
  712. }
  713. contextPrototype.translate = function(aX, aY) {
  714. var m1 = [
  715. [1, 0, 0],
  716. [0, 1, 0],
  717. [aX, aY, 1]
  718. ];
  719. setM(this, matrixMultiply(m1, this.m_), false);
  720. };
  721. contextPrototype.rotate = function(aRot) {
  722. var c = mc(aRot);
  723. var s = ms(aRot);
  724. var m1 = [
  725. [c, s, 0],
  726. [-s, c, 0],
  727. [0, 0, 1]
  728. ];
  729. setM(this, matrixMultiply(m1, this.m_), false);
  730. };
  731. contextPrototype.scale = function(aX, aY) {
  732. this.arcScaleX_ *= aX;
  733. this.arcScaleY_ *= aY;
  734. var m1 = [
  735. [aX, 0, 0],
  736. [0, aY, 0],
  737. [0, 0, 1]
  738. ];
  739. setM(this, matrixMultiply(m1, this.m_), true);
  740. };
  741. contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) {
  742. var m1 = [
  743. [m11, m12, 0],
  744. [m21, m22, 0],
  745. [dx, dy, 1]
  746. ];
  747. setM(this, matrixMultiply(m1, this.m_), true);
  748. };
  749. contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) {
  750. var m = [
  751. [m11, m12, 0],
  752. [m21, m22, 0],
  753. [dx, dy, 1]
  754. ];
  755. setM(this, m, true);
  756. };
  757. /******** STUBS ********/
  758. contextPrototype.clip = function() {
  759. // TODO: Implement
  760. };
  761. contextPrototype.arcTo = function() {
  762. // TODO: Implement
  763. };
  764. contextPrototype.createPattern = function() {
  765. return new CanvasPattern_;
  766. };
  767. // Gradient / Pattern Stubs
  768. function CanvasGradient_(aType) {
  769. this.type_ = aType;
  770. this.x0_ = 0;
  771. this.y0_ = 0;
  772. this.r0_ = 0;
  773. this.x1_ = 0;
  774. this.y1_ = 0;
  775. this.r1_ = 0;
  776. this.colors_ = [];
  777. }
  778. CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) {
  779. aColor = processStyle(aColor);
  780. this.colors_.push({offset: aOffset,
  781. color: aColor.color,
  782. alpha: aColor.alpha});
  783. };
  784. function CanvasPattern_() {}
  785. // set up externs
  786. G_vmlCanvasManager = G_vmlCanvasManager_;
  787. CanvasRenderingContext2D = CanvasRenderingContext2D_;
  788. CanvasGradient = CanvasGradient_;
  789. CanvasPattern = CanvasPattern_;
  790. })();
  791. } // if