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.

924 lines
26 KiB

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