├── AUTHORS ├── COPYING ├── README ├── bower.json ├── examples ├── example1.html ├── example2.html ├── example3.html └── ff.jpg ├── excanvas.js ├── silverlight └── excanvas.js └── testcases ├── arc.html ├── clearpath.html ├── colors.html ├── draw-image-flip.html ├── drawimage.html ├── gradient.html ├── gradient2.html ├── linewidth.html ├── overflow.html ├── overlay.html ├── pattern.html ├── pattern.jpg ├── quadraticcurve.html ├── resizing.html ├── saverestorepath.html ├── stroke-scale-rotate.html ├── stroke-should-not-close-path.html └── text.html /AUTHORS: -------------------------------------------------------------------------------- 1 | ExplorerCanvas 2 | 3 | Google Open Source: 4 | 5 | 6 | 7 | Developers: 8 | Emil A Eklund 9 | Erik Arvidsson 10 | Glen Murphy -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | ExplorerCanvas 2 | Copyright 2006 Google Inc. 3 | 4 | ------------------------------------------------------------------------------- 5 | DESCRIPTION 6 | 7 | Firefox, Safari and Opera 9 support the canvas tag to allow 2D command-based 8 | drawing operations. ExplorerCanvas brings the same functionality to Internet 9 | Explorer; web developers only need to include a single script tag in their 10 | existing canvas webpages to enable this support. 11 | 12 | 13 | ------------------------------------------------------------------------------- 14 | INSTALLATION 15 | 16 | Include the ExplorerCanvas tag in the same directory as your HTML files, and 17 | add the following code to your page, preferably in the tag. 18 | 19 | 20 | 21 | If you run into trouble, please look at the included example code to see how 22 | to best implement this 23 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ExplorerCanvas", 3 | "version": "1.0.0", 4 | "main": "excanvas.js", 5 | "homepage": "https://code.google.com/p/explorercanvas/", 6 | "authors": [ 7 | "Google Open Source", 8 | "Emil A Eklund", 9 | "Erik Arvidsson", 10 | "Glen Murphy" 11 | ], 12 | "keywords": [ 13 | "javascript", 14 | "canvas" 15 | ], 16 | "description": "Modern browsers all support the HTML5 canvas tag to allow 2D command-based drawing. ExplorerCanvas brings the same functionality to old versions of Internet Explorer (Internet Explorer 9+ supports canvas natively). To use, web developers only need to include a single script tag in their existing web pages.", 17 | "license": "Apache License, Version 2.0", 18 | "ignore": [ 19 | "examples", 20 | "testcases", 21 | "test", 22 | "AUTHORS", 23 | "COPYING", 24 | "README" 25 | ] 26 | } -------------------------------------------------------------------------------- /examples/example1.html: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | ExplorerCanvas Example 1 19 | 20 | 78 | 89 | 90 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /examples/example2.html: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | ExplorerCanvas Example 1 19 | 20 | 502 | 509 | 510 | 511 | 512 | 513 | -------------------------------------------------------------------------------- /examples/example3.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 57 | 267 | 268 | 269 | 270 |
271 |
272 | 273 |
274 | 275 | 276 |
277 | 281 | 282 | 283 | 284 | 285 | -------------------------------------------------------------------------------- /examples/ff.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arv/ExplorerCanvas/44ac99ffc23b665c94a56b365d1d98ffa567e42c/examples/ff.jpg -------------------------------------------------------------------------------- /excanvas.js: -------------------------------------------------------------------------------- 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 | 15 | 16 | // Known Issues: 17 | // 18 | // * Patterns only support repeat. 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 | 34 | // Only add this code if we do not already have a canvas implementation 35 | if (!document.createElement('canvas').getContext) { 36 | 37 | (function() { 38 | 39 | // alias some functions to make (compiled) code shorter 40 | var m = Math; 41 | var mr = m.round; 42 | var ms = m.sin; 43 | var mc = m.cos; 44 | var abs = m.abs; 45 | var sqrt = m.sqrt; 46 | 47 | // this is used for sub pixel precision 48 | var Z = 10; 49 | var Z2 = Z / 2; 50 | 51 | /** 52 | * This funtion is assigned to the elements as element.getContext(). 53 | * @this {HTMLElement} 54 | * @return {CanvasRenderingContext2D_} 55 | */ 56 | function getContext() { 57 | return this.context_ || 58 | (this.context_ = new CanvasRenderingContext2D_(this)); 59 | } 60 | 61 | var slice = Array.prototype.slice; 62 | 63 | /** 64 | * Binds a function to an object. The returned function will always use the 65 | * passed in {@code obj} as {@code this}. 66 | * 67 | * Example: 68 | * 69 | * g = bind(f, obj, a, b) 70 | * g(c, d) // will do f.call(obj, a, b, c, d) 71 | * 72 | * @param {Function} f The function to bind the object to 73 | * @param {Object} obj The object that should act as this when the function 74 | * is called 75 | * @param {*} var_args Rest arguments that will be used as the initial 76 | * arguments when the function is called 77 | * @return {Function} A new function that has bound this 78 | */ 79 | function bind(f, obj, var_args) { 80 | var a = slice.call(arguments, 2); 81 | return function() { 82 | return f.apply(obj, a.concat(slice.call(arguments))); 83 | }; 84 | } 85 | 86 | function encodeHtmlAttribute(s) { 87 | return String(s).replace(/&/g, '&').replace(/"/g, '"'); 88 | } 89 | 90 | function addNamespace(doc, prefix, urn) { 91 | if (!doc.namespaces[prefix]) { 92 | doc.namespaces.add(prefix, urn, '#default#VML'); 93 | } 94 | } 95 | 96 | function addNamespacesAndStylesheet(doc) { 97 | addNamespace(doc, 'g_vml_', 'urn:schemas-microsoft-com:vml'); 98 | addNamespace(doc, 'g_o_', 'urn:schemas-microsoft-com:office:office'); 99 | 100 | // Setup default CSS. Only add one style sheet per document 101 | if (!doc.styleSheets['ex_canvas_']) { 102 | var ss = doc.createStyleSheet(); 103 | ss.owningElement.id = 'ex_canvas_'; 104 | ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + 105 | // default size is 300x150 in Gecko and Opera 106 | 'text-align:left;width:300px;height:150px}'; 107 | } 108 | } 109 | 110 | // Add namespaces and stylesheet at startup. 111 | addNamespacesAndStylesheet(document); 112 | 113 | var G_vmlCanvasManager_ = { 114 | init: function(opt_doc) { 115 | var doc = opt_doc || document; 116 | // Create a dummy element so that IE will allow canvas elements to be 117 | // recognized. 118 | doc.createElement('canvas'); 119 | doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); 120 | }, 121 | 122 | init_: function(doc) { 123 | // find all canvas elements 124 | var els = doc.getElementsByTagName('canvas'); 125 | for (var i = 0; i < els.length; i++) { 126 | this.initElement(els[i]); 127 | } 128 | }, 129 | 130 | /** 131 | * Public initializes a canvas element so that it can be used as canvas 132 | * element from now on. This is called automatically before the page is 133 | * loaded but if you are creating elements using createElement you need to 134 | * make sure this is called on the element. 135 | * @param {HTMLElement} el The canvas element to initialize. 136 | * @return {HTMLElement} the element that was created. 137 | */ 138 | initElement: function(el) { 139 | if (!el.getContext) { 140 | el.getContext = getContext; 141 | 142 | // Add namespaces and stylesheet to document of the element. 143 | addNamespacesAndStylesheet(el.ownerDocument); 144 | 145 | // Remove fallback content. There is no way to hide text nodes so we 146 | // just remove all childNodes. We could hide all elements and remove 147 | // text nodes but who really cares about the fallback content. 148 | el.innerHTML = ''; 149 | 150 | // do not use inline function because that will leak memory 151 | el.attachEvent('onpropertychange', onPropertyChange); 152 | el.attachEvent('onresize', onResize); 153 | 154 | var attrs = el.attributes; 155 | if (attrs.width && attrs.width.specified) { 156 | // TODO: use runtimeStyle and coordsize 157 | // el.getContext().setWidth_(attrs.width.nodeValue); 158 | el.style.width = attrs.width.nodeValue + 'px'; 159 | } else { 160 | el.width = el.clientWidth; 161 | } 162 | if (attrs.height && attrs.height.specified) { 163 | // TODO: use runtimeStyle and coordsize 164 | // el.getContext().setHeight_(attrs.height.nodeValue); 165 | el.style.height = attrs.height.nodeValue + 'px'; 166 | } else { 167 | el.height = el.clientHeight; 168 | } 169 | //el.getContext().setCoordsize_() 170 | } 171 | return el; 172 | } 173 | }; 174 | 175 | function onPropertyChange(e) { 176 | var el = e.srcElement; 177 | 178 | switch (e.propertyName) { 179 | case 'width': 180 | el.getContext().clearRect(); 181 | el.style.width = el.attributes.width.nodeValue + 'px'; 182 | // In IE8 this does not trigger onresize. 183 | el.firstChild.style.width = el.clientWidth + 'px'; 184 | break; 185 | case 'height': 186 | el.getContext().clearRect(); 187 | el.style.height = el.attributes.height.nodeValue + 'px'; 188 | el.firstChild.style.height = el.clientHeight + 'px'; 189 | break; 190 | } 191 | } 192 | 193 | function onResize(e) { 194 | var el = e.srcElement; 195 | if (el.firstChild) { 196 | el.firstChild.style.width = el.clientWidth + 'px'; 197 | el.firstChild.style.height = el.clientHeight + 'px'; 198 | } 199 | } 200 | 201 | G_vmlCanvasManager_.init(); 202 | 203 | // precompute "00" to "FF" 204 | var decToHex = []; 205 | for (var i = 0; i < 16; i++) { 206 | for (var j = 0; j < 16; j++) { 207 | decToHex[i * 16 + j] = i.toString(16) + j.toString(16); 208 | } 209 | } 210 | 211 | function createMatrixIdentity() { 212 | return [ 213 | [1, 0, 0], 214 | [0, 1, 0], 215 | [0, 0, 1] 216 | ]; 217 | } 218 | 219 | function matrixMultiply(m1, m2) { 220 | var result = createMatrixIdentity(); 221 | 222 | for (var x = 0; x < 3; x++) { 223 | for (var y = 0; y < 3; y++) { 224 | var sum = 0; 225 | 226 | for (var z = 0; z < 3; z++) { 227 | sum += m1[x][z] * m2[z][y]; 228 | } 229 | 230 | result[x][y] = sum; 231 | } 232 | } 233 | return result; 234 | } 235 | 236 | function copyState(o1, o2) { 237 | o2.fillStyle = o1.fillStyle; 238 | o2.lineCap = o1.lineCap; 239 | o2.lineJoin = o1.lineJoin; 240 | o2.lineWidth = o1.lineWidth; 241 | o2.miterLimit = o1.miterLimit; 242 | o2.shadowBlur = o1.shadowBlur; 243 | o2.shadowColor = o1.shadowColor; 244 | o2.shadowOffsetX = o1.shadowOffsetX; 245 | o2.shadowOffsetY = o1.shadowOffsetY; 246 | o2.strokeStyle = o1.strokeStyle; 247 | o2.globalAlpha = o1.globalAlpha; 248 | o2.font = o1.font; 249 | o2.textAlign = o1.textAlign; 250 | o2.textBaseline = o1.textBaseline; 251 | o2.arcScaleX_ = o1.arcScaleX_; 252 | o2.arcScaleY_ = o1.arcScaleY_; 253 | o2.lineScale_ = o1.lineScale_; 254 | } 255 | 256 | var colorData = { 257 | aliceblue: '#F0F8FF', 258 | antiquewhite: '#FAEBD7', 259 | aquamarine: '#7FFFD4', 260 | azure: '#F0FFFF', 261 | beige: '#F5F5DC', 262 | bisque: '#FFE4C4', 263 | black: '#000000', 264 | blanchedalmond: '#FFEBCD', 265 | blueviolet: '#8A2BE2', 266 | brown: '#A52A2A', 267 | burlywood: '#DEB887', 268 | cadetblue: '#5F9EA0', 269 | chartreuse: '#7FFF00', 270 | chocolate: '#D2691E', 271 | coral: '#FF7F50', 272 | cornflowerblue: '#6495ED', 273 | cornsilk: '#FFF8DC', 274 | crimson: '#DC143C', 275 | cyan: '#00FFFF', 276 | darkblue: '#00008B', 277 | darkcyan: '#008B8B', 278 | darkgoldenrod: '#B8860B', 279 | darkgray: '#A9A9A9', 280 | darkgreen: '#006400', 281 | darkgrey: '#A9A9A9', 282 | darkkhaki: '#BDB76B', 283 | darkmagenta: '#8B008B', 284 | darkolivegreen: '#556B2F', 285 | darkorange: '#FF8C00', 286 | darkorchid: '#9932CC', 287 | darkred: '#8B0000', 288 | darksalmon: '#E9967A', 289 | darkseagreen: '#8FBC8F', 290 | darkslateblue: '#483D8B', 291 | darkslategray: '#2F4F4F', 292 | darkslategrey: '#2F4F4F', 293 | darkturquoise: '#00CED1', 294 | darkviolet: '#9400D3', 295 | deeppink: '#FF1493', 296 | deepskyblue: '#00BFFF', 297 | dimgray: '#696969', 298 | dimgrey: '#696969', 299 | dodgerblue: '#1E90FF', 300 | firebrick: '#B22222', 301 | floralwhite: '#FFFAF0', 302 | forestgreen: '#228B22', 303 | gainsboro: '#DCDCDC', 304 | ghostwhite: '#F8F8FF', 305 | gold: '#FFD700', 306 | goldenrod: '#DAA520', 307 | grey: '#808080', 308 | greenyellow: '#ADFF2F', 309 | honeydew: '#F0FFF0', 310 | hotpink: '#FF69B4', 311 | indianred: '#CD5C5C', 312 | indigo: '#4B0082', 313 | ivory: '#FFFFF0', 314 | khaki: '#F0E68C', 315 | lavender: '#E6E6FA', 316 | lavenderblush: '#FFF0F5', 317 | lawngreen: '#7CFC00', 318 | lemonchiffon: '#FFFACD', 319 | lightblue: '#ADD8E6', 320 | lightcoral: '#F08080', 321 | lightcyan: '#E0FFFF', 322 | lightgoldenrodyellow: '#FAFAD2', 323 | lightgreen: '#90EE90', 324 | lightgrey: '#D3D3D3', 325 | lightpink: '#FFB6C1', 326 | lightsalmon: '#FFA07A', 327 | lightseagreen: '#20B2AA', 328 | lightskyblue: '#87CEFA', 329 | lightslategray: '#778899', 330 | lightslategrey: '#778899', 331 | lightsteelblue: '#B0C4DE', 332 | lightyellow: '#FFFFE0', 333 | limegreen: '#32CD32', 334 | linen: '#FAF0E6', 335 | magenta: '#FF00FF', 336 | mediumaquamarine: '#66CDAA', 337 | mediumblue: '#0000CD', 338 | mediumorchid: '#BA55D3', 339 | mediumpurple: '#9370DB', 340 | mediumseagreen: '#3CB371', 341 | mediumslateblue: '#7B68EE', 342 | mediumspringgreen: '#00FA9A', 343 | mediumturquoise: '#48D1CC', 344 | mediumvioletred: '#C71585', 345 | midnightblue: '#191970', 346 | mintcream: '#F5FFFA', 347 | mistyrose: '#FFE4E1', 348 | moccasin: '#FFE4B5', 349 | navajowhite: '#FFDEAD', 350 | oldlace: '#FDF5E6', 351 | olivedrab: '#6B8E23', 352 | orange: '#FFA500', 353 | orangered: '#FF4500', 354 | orchid: '#DA70D6', 355 | palegoldenrod: '#EEE8AA', 356 | palegreen: '#98FB98', 357 | paleturquoise: '#AFEEEE', 358 | palevioletred: '#DB7093', 359 | papayawhip: '#FFEFD5', 360 | peachpuff: '#FFDAB9', 361 | peru: '#CD853F', 362 | pink: '#FFC0CB', 363 | plum: '#DDA0DD', 364 | powderblue: '#B0E0E6', 365 | rosybrown: '#BC8F8F', 366 | royalblue: '#4169E1', 367 | saddlebrown: '#8B4513', 368 | salmon: '#FA8072', 369 | sandybrown: '#F4A460', 370 | seagreen: '#2E8B57', 371 | seashell: '#FFF5EE', 372 | sienna: '#A0522D', 373 | skyblue: '#87CEEB', 374 | slateblue: '#6A5ACD', 375 | slategray: '#708090', 376 | slategrey: '#708090', 377 | snow: '#FFFAFA', 378 | springgreen: '#00FF7F', 379 | steelblue: '#4682B4', 380 | tan: '#D2B48C', 381 | thistle: '#D8BFD8', 382 | tomato: '#FF6347', 383 | turquoise: '#40E0D0', 384 | violet: '#EE82EE', 385 | wheat: '#F5DEB3', 386 | whitesmoke: '#F5F5F5', 387 | yellowgreen: '#9ACD32' 388 | }; 389 | 390 | 391 | function getRgbHslContent(styleString) { 392 | var start = styleString.indexOf('(', 3); 393 | var end = styleString.indexOf(')', start + 1); 394 | var parts = styleString.substring(start + 1, end).split(','); 395 | // add alpha if needed 396 | if (parts.length != 4 || styleString.charAt(3) != 'a') { 397 | parts[3] = 1; 398 | } 399 | return parts; 400 | } 401 | 402 | function percent(s) { 403 | return parseFloat(s) / 100; 404 | } 405 | 406 | function clamp(v, min, max) { 407 | return Math.min(max, Math.max(min, v)); 408 | } 409 | 410 | function hslToRgb(parts){ 411 | var r, g, b, h, s, l; 412 | h = parseFloat(parts[0]) / 360 % 360; 413 | if (h < 0) 414 | h++; 415 | s = clamp(percent(parts[1]), 0, 1); 416 | l = clamp(percent(parts[2]), 0, 1); 417 | if (s == 0) { 418 | r = g = b = l; // achromatic 419 | } else { 420 | var q = l < 0.5 ? l * (1 + s) : l + s - l * s; 421 | var p = 2 * l - q; 422 | r = hueToRgb(p, q, h + 1 / 3); 423 | g = hueToRgb(p, q, h); 424 | b = hueToRgb(p, q, h - 1 / 3); 425 | } 426 | 427 | return '#' + decToHex[Math.floor(r * 255)] + 428 | decToHex[Math.floor(g * 255)] + 429 | decToHex[Math.floor(b * 255)]; 430 | } 431 | 432 | function hueToRgb(m1, m2, h) { 433 | if (h < 0) 434 | h++; 435 | if (h > 1) 436 | h--; 437 | 438 | if (6 * h < 1) 439 | return m1 + (m2 - m1) * 6 * h; 440 | else if (2 * h < 1) 441 | return m2; 442 | else if (3 * h < 2) 443 | return m1 + (m2 - m1) * (2 / 3 - h) * 6; 444 | else 445 | return m1; 446 | } 447 | 448 | var processStyleCache = {}; 449 | 450 | function processStyle(styleString) { 451 | if (styleString in processStyleCache) { 452 | return processStyleCache[styleString]; 453 | } 454 | 455 | var str, alpha = 1; 456 | 457 | styleString = String(styleString); 458 | if (styleString.charAt(0) == '#') { 459 | str = styleString; 460 | } else if (/^rgb/.test(styleString)) { 461 | var parts = getRgbHslContent(styleString); 462 | var str = '#', n; 463 | for (var i = 0; i < 3; i++) { 464 | if (parts[i].indexOf('%') != -1) { 465 | n = Math.floor(percent(parts[i]) * 255); 466 | } else { 467 | n = +parts[i]; 468 | } 469 | str += decToHex[clamp(n, 0, 255)]; 470 | } 471 | alpha = +parts[3]; 472 | } else if (/^hsl/.test(styleString)) { 473 | var parts = getRgbHslContent(styleString); 474 | str = hslToRgb(parts); 475 | alpha = parts[3]; 476 | } else { 477 | str = colorData[styleString] || styleString; 478 | } 479 | return processStyleCache[styleString] = {color: str, alpha: alpha}; 480 | } 481 | 482 | var DEFAULT_STYLE = { 483 | style: 'normal', 484 | variant: 'normal', 485 | weight: 'normal', 486 | size: 10, 487 | family: 'sans-serif' 488 | }; 489 | 490 | // Internal text style cache 491 | var fontStyleCache = {}; 492 | 493 | function processFontStyle(styleString) { 494 | if (fontStyleCache[styleString]) { 495 | return fontStyleCache[styleString]; 496 | } 497 | 498 | var el = document.createElement('div'); 499 | var style = el.style; 500 | try { 501 | style.font = styleString; 502 | } catch (ex) { 503 | // Ignore failures to set to invalid font. 504 | } 505 | 506 | return fontStyleCache[styleString] = { 507 | style: style.fontStyle || DEFAULT_STYLE.style, 508 | variant: style.fontVariant || DEFAULT_STYLE.variant, 509 | weight: style.fontWeight || DEFAULT_STYLE.weight, 510 | size: style.fontSize || DEFAULT_STYLE.size, 511 | family: style.fontFamily || DEFAULT_STYLE.family 512 | }; 513 | } 514 | 515 | function getComputedStyle(style, element) { 516 | var computedStyle = {}; 517 | 518 | for (var p in style) { 519 | computedStyle[p] = style[p]; 520 | } 521 | 522 | // Compute the size 523 | var canvasFontSize = parseFloat(element.currentStyle.fontSize), 524 | fontSize = parseFloat(style.size); 525 | 526 | if (typeof style.size == 'number') { 527 | computedStyle.size = style.size; 528 | } else if (style.size.indexOf('px') != -1) { 529 | computedStyle.size = fontSize; 530 | } else if (style.size.indexOf('em') != -1) { 531 | computedStyle.size = canvasFontSize * fontSize; 532 | } else if(style.size.indexOf('%') != -1) { 533 | computedStyle.size = (canvasFontSize / 100) * fontSize; 534 | } else if (style.size.indexOf('pt') != -1) { 535 | computedStyle.size = fontSize / .75; 536 | } else { 537 | computedStyle.size = canvasFontSize; 538 | } 539 | 540 | // Different scaling between normal text and VML text. This was found using 541 | // trial and error to get the same size as non VML text. 542 | computedStyle.size *= 0.981; 543 | 544 | return computedStyle; 545 | } 546 | 547 | function buildStyle(style) { 548 | return style.style + ' ' + style.variant + ' ' + style.weight + ' ' + 549 | style.size + 'px ' + style.family; 550 | } 551 | 552 | var lineCapMap = { 553 | 'butt': 'flat', 554 | 'round': 'round' 555 | }; 556 | 557 | function processLineCap(lineCap) { 558 | return lineCapMap[lineCap] || 'square'; 559 | } 560 | 561 | /** 562 | * This class implements CanvasRenderingContext2D interface as described by 563 | * the WHATWG. 564 | * @param {HTMLElement} canvasElement The element that the 2D context should 565 | * be associated with 566 | */ 567 | function CanvasRenderingContext2D_(canvasElement) { 568 | this.m_ = createMatrixIdentity(); 569 | 570 | this.mStack_ = []; 571 | this.aStack_ = []; 572 | this.currentPath_ = []; 573 | 574 | // Canvas context properties 575 | this.strokeStyle = '#000'; 576 | this.fillStyle = '#000'; 577 | 578 | this.lineWidth = 1; 579 | this.lineJoin = 'miter'; 580 | this.lineCap = 'butt'; 581 | this.miterLimit = Z * 1; 582 | this.globalAlpha = 1; 583 | this.font = '10px sans-serif'; 584 | this.textAlign = 'left'; 585 | this.textBaseline = 'alphabetic'; 586 | this.canvas = canvasElement; 587 | 588 | var cssText = 'width:' + canvasElement.clientWidth + 'px;height:' + 589 | canvasElement.clientHeight + 'px;overflow:hidden;position:absolute'; 590 | var el = canvasElement.ownerDocument.createElement('div'); 591 | el.style.cssText = cssText; 592 | canvasElement.appendChild(el); 593 | 594 | var overlayEl = el.cloneNode(false); 595 | // Use a non transparent background. 596 | overlayEl.style.backgroundColor = 'red'; 597 | overlayEl.style.filter = 'alpha(opacity=0)'; 598 | canvasElement.appendChild(overlayEl); 599 | 600 | this.element_ = el; 601 | this.arcScaleX_ = 1; 602 | this.arcScaleY_ = 1; 603 | this.lineScale_ = 1; 604 | } 605 | 606 | var contextPrototype = CanvasRenderingContext2D_.prototype; 607 | contextPrototype.clearRect = function() { 608 | if (this.textMeasureEl_) { 609 | this.textMeasureEl_.removeNode(true); 610 | this.textMeasureEl_ = null; 611 | } 612 | this.element_.innerHTML = ''; 613 | }; 614 | 615 | contextPrototype.beginPath = function() { 616 | // TODO: Branch current matrix so that save/restore has no effect 617 | // as per safari docs. 618 | this.currentPath_ = []; 619 | }; 620 | 621 | contextPrototype.moveTo = function(aX, aY) { 622 | var p = getCoords(this, aX, aY); 623 | this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y}); 624 | this.currentX_ = p.x; 625 | this.currentY_ = p.y; 626 | }; 627 | 628 | contextPrototype.lineTo = function(aX, aY) { 629 | var p = getCoords(this, aX, aY); 630 | this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y}); 631 | 632 | this.currentX_ = p.x; 633 | this.currentY_ = p.y; 634 | }; 635 | 636 | contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, 637 | aCP2x, aCP2y, 638 | aX, aY) { 639 | var p = getCoords(this, aX, aY); 640 | var cp1 = getCoords(this, aCP1x, aCP1y); 641 | var cp2 = getCoords(this, aCP2x, aCP2y); 642 | bezierCurveTo(this, cp1, cp2, p); 643 | }; 644 | 645 | // Helper function that takes the already fixed cordinates. 646 | function bezierCurveTo(self, cp1, cp2, p) { 647 | self.currentPath_.push({ 648 | type: 'bezierCurveTo', 649 | cp1x: cp1.x, 650 | cp1y: cp1.y, 651 | cp2x: cp2.x, 652 | cp2y: cp2.y, 653 | x: p.x, 654 | y: p.y 655 | }); 656 | self.currentX_ = p.x; 657 | self.currentY_ = p.y; 658 | } 659 | 660 | contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { 661 | // the following is lifted almost directly from 662 | // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes 663 | 664 | var cp = getCoords(this, aCPx, aCPy); 665 | var p = getCoords(this, aX, aY); 666 | 667 | var cp1 = { 668 | x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), 669 | y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) 670 | }; 671 | var cp2 = { 672 | x: cp1.x + (p.x - this.currentX_) / 3.0, 673 | y: cp1.y + (p.y - this.currentY_) / 3.0 674 | }; 675 | 676 | bezierCurveTo(this, cp1, cp2, p); 677 | }; 678 | 679 | contextPrototype.arc = function(aX, aY, aRadius, 680 | aStartAngle, aEndAngle, aClockwise) { 681 | aRadius *= Z; 682 | var arcType = aClockwise ? 'at' : 'wa'; 683 | 684 | var xStart = aX + mc(aStartAngle) * aRadius - Z2; 685 | var yStart = aY + ms(aStartAngle) * aRadius - Z2; 686 | 687 | var xEnd = aX + mc(aEndAngle) * aRadius - Z2; 688 | var yEnd = aY + ms(aEndAngle) * aRadius - Z2; 689 | 690 | // IE won't render arches drawn counter clockwise if xStart == xEnd. 691 | if (xStart == xEnd && !aClockwise) { 692 | xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something 693 | // that can be represented in binary 694 | } 695 | 696 | var p = getCoords(this, aX, aY); 697 | var pStart = getCoords(this, xStart, yStart); 698 | var pEnd = getCoords(this, xEnd, yEnd); 699 | 700 | this.currentPath_.push({type: arcType, 701 | x: p.x, 702 | y: p.y, 703 | radius: aRadius, 704 | xStart: pStart.x, 705 | yStart: pStart.y, 706 | xEnd: pEnd.x, 707 | yEnd: pEnd.y}); 708 | 709 | }; 710 | 711 | contextPrototype.rect = function(aX, aY, aWidth, aHeight) { 712 | this.moveTo(aX, aY); 713 | this.lineTo(aX + aWidth, aY); 714 | this.lineTo(aX + aWidth, aY + aHeight); 715 | this.lineTo(aX, aY + aHeight); 716 | this.closePath(); 717 | }; 718 | 719 | contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { 720 | var oldPath = this.currentPath_; 721 | this.beginPath(); 722 | 723 | this.moveTo(aX, aY); 724 | this.lineTo(aX + aWidth, aY); 725 | this.lineTo(aX + aWidth, aY + aHeight); 726 | this.lineTo(aX, aY + aHeight); 727 | this.closePath(); 728 | this.stroke(); 729 | 730 | this.currentPath_ = oldPath; 731 | }; 732 | 733 | contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { 734 | var oldPath = this.currentPath_; 735 | this.beginPath(); 736 | 737 | this.moveTo(aX, aY); 738 | this.lineTo(aX + aWidth, aY); 739 | this.lineTo(aX + aWidth, aY + aHeight); 740 | this.lineTo(aX, aY + aHeight); 741 | this.closePath(); 742 | this.fill(); 743 | 744 | this.currentPath_ = oldPath; 745 | }; 746 | 747 | contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { 748 | var gradient = new CanvasGradient_('gradient'); 749 | gradient.x0_ = aX0; 750 | gradient.y0_ = aY0; 751 | gradient.x1_ = aX1; 752 | gradient.y1_ = aY1; 753 | return gradient; 754 | }; 755 | 756 | contextPrototype.createRadialGradient = function(aX0, aY0, aR0, 757 | aX1, aY1, aR1) { 758 | var gradient = new CanvasGradient_('gradientradial'); 759 | gradient.x0_ = aX0; 760 | gradient.y0_ = aY0; 761 | gradient.r0_ = aR0; 762 | gradient.x1_ = aX1; 763 | gradient.y1_ = aY1; 764 | gradient.r1_ = aR1; 765 | return gradient; 766 | }; 767 | 768 | contextPrototype.drawImage = function(image, var_args) { 769 | var dx, dy, dw, dh, sx, sy, sw, sh; 770 | 771 | // to find the original width we overide the width and height 772 | var oldRuntimeWidth = image.runtimeStyle.width; 773 | var oldRuntimeHeight = image.runtimeStyle.height; 774 | image.runtimeStyle.width = 'auto'; 775 | image.runtimeStyle.height = 'auto'; 776 | 777 | // get the original size 778 | var w = image.width; 779 | var h = image.height; 780 | 781 | // and remove overides 782 | image.runtimeStyle.width = oldRuntimeWidth; 783 | image.runtimeStyle.height = oldRuntimeHeight; 784 | 785 | if (arguments.length == 3) { 786 | dx = arguments[1]; 787 | dy = arguments[2]; 788 | sx = sy = 0; 789 | sw = dw = w; 790 | sh = dh = h; 791 | } else if (arguments.length == 5) { 792 | dx = arguments[1]; 793 | dy = arguments[2]; 794 | dw = arguments[3]; 795 | dh = arguments[4]; 796 | sx = sy = 0; 797 | sw = w; 798 | sh = h; 799 | } else if (arguments.length == 9) { 800 | sx = arguments[1]; 801 | sy = arguments[2]; 802 | sw = arguments[3]; 803 | sh = arguments[4]; 804 | dx = arguments[5]; 805 | dy = arguments[6]; 806 | dw = arguments[7]; 807 | dh = arguments[8]; 808 | } else { 809 | throw Error('Invalid number of arguments'); 810 | } 811 | 812 | var d = getCoords(this, dx, dy); 813 | 814 | var w2 = sw / 2; 815 | var h2 = sh / 2; 816 | 817 | var vmlStr = []; 818 | 819 | var W = 10; 820 | var H = 10; 821 | 822 | // For some reason that I've now forgotten, using divs didn't work 823 | vmlStr.push(' ' , 864 | '', 872 | ''); 873 | 874 | this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); 875 | }; 876 | 877 | contextPrototype.stroke = function(aFill) { 878 | var lineStr = []; 879 | var lineOpen = false; 880 | 881 | var W = 10; 882 | var H = 10; 883 | 884 | lineStr.push(''); 952 | 953 | if (!aFill) { 954 | appendStroke(this, lineStr); 955 | } else { 956 | appendFill(this, lineStr, min, max); 957 | } 958 | 959 | lineStr.push(''); 960 | 961 | this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); 962 | }; 963 | 964 | function appendStroke(ctx, lineStr) { 965 | var a = processStyle(ctx.strokeStyle); 966 | var color = a.color; 967 | var opacity = a.alpha * ctx.globalAlpha; 968 | var lineWidth = ctx.lineScale_ * ctx.lineWidth; 969 | 970 | // VML cannot correctly render a line if the width is less than 1px. 971 | // In that case, we dilute the color to make the line look thinner. 972 | if (lineWidth < 1) { 973 | opacity *= lineWidth; 974 | } 975 | 976 | lineStr.push( 977 | '' 984 | ); 985 | } 986 | 987 | function appendFill(ctx, lineStr, min, max) { 988 | var fillStyle = ctx.fillStyle; 989 | var arcScaleX = ctx.arcScaleX_; 990 | var arcScaleY = ctx.arcScaleY_; 991 | var width = max.x - min.x; 992 | var height = max.y - min.y; 993 | if (fillStyle instanceof CanvasGradient_) { 994 | // TODO: Gradients transformed with the transformation matrix. 995 | var angle = 0; 996 | var focus = {x: 0, y: 0}; 997 | 998 | // additional offset 999 | var shift = 0; 1000 | // scale factor for offset 1001 | var expansion = 1; 1002 | 1003 | if (fillStyle.type_ == 'gradient') { 1004 | var x0 = fillStyle.x0_ / arcScaleX; 1005 | var y0 = fillStyle.y0_ / arcScaleY; 1006 | var x1 = fillStyle.x1_ / arcScaleX; 1007 | var y1 = fillStyle.y1_ / arcScaleY; 1008 | var p0 = getCoords(ctx, x0, y0); 1009 | var p1 = getCoords(ctx, x1, y1); 1010 | var dx = p1.x - p0.x; 1011 | var dy = p1.y - p0.y; 1012 | angle = Math.atan2(dx, dy) * 180 / Math.PI; 1013 | 1014 | // The angle should be a non-negative number. 1015 | if (angle < 0) { 1016 | angle += 360; 1017 | } 1018 | 1019 | // Very small angles produce an unexpected result because they are 1020 | // converted to a scientific notation string. 1021 | if (angle < 1e-6) { 1022 | angle = 0; 1023 | } 1024 | } else { 1025 | var p0 = getCoords(ctx, fillStyle.x0_, fillStyle.y0_); 1026 | focus = { 1027 | x: (p0.x - min.x) / width, 1028 | y: (p0.y - min.y) / height 1029 | }; 1030 | 1031 | width /= arcScaleX * Z; 1032 | height /= arcScaleY * Z; 1033 | var dimension = m.max(width, height); 1034 | shift = 2 * fillStyle.r0_ / dimension; 1035 | expansion = 2 * fillStyle.r1_ / dimension - shift; 1036 | } 1037 | 1038 | // We need to sort the color stops in ascending order by offset, 1039 | // otherwise IE won't interpret it correctly. 1040 | var stops = fillStyle.colors_; 1041 | stops.sort(function(cs1, cs2) { 1042 | return cs1.offset - cs2.offset; 1043 | }); 1044 | 1045 | var length = stops.length; 1046 | var color1 = stops[0].color; 1047 | var color2 = stops[length - 1].color; 1048 | var opacity1 = stops[0].alpha * ctx.globalAlpha; 1049 | var opacity2 = stops[length - 1].alpha * ctx.globalAlpha; 1050 | 1051 | var colors = []; 1052 | for (var i = 0; i < length; i++) { 1053 | var stop = stops[i]; 1054 | colors.push(stop.offset * expansion + shift + ' ' + stop.color); 1055 | } 1056 | 1057 | // When colors attribute is used, the meanings of opacity and o:opacity2 1058 | // are reversed. 1059 | lineStr.push(''); 1068 | } else if (fillStyle instanceof CanvasPattern_) { 1069 | if (width && height) { 1070 | var deltaLeft = -min.x; 1071 | var deltaTop = -min.y; 1072 | lineStr.push(''); 1080 | } 1081 | } else { 1082 | var a = processStyle(ctx.fillStyle); 1083 | var color = a.color; 1084 | var opacity = a.alpha * ctx.globalAlpha; 1085 | lineStr.push(''); 1087 | } 1088 | } 1089 | 1090 | contextPrototype.fill = function() { 1091 | this.stroke(true); 1092 | }; 1093 | 1094 | contextPrototype.closePath = function() { 1095 | this.currentPath_.push({type: 'close'}); 1096 | }; 1097 | 1098 | function getCoords(ctx, aX, aY) { 1099 | var m = ctx.m_; 1100 | return { 1101 | x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, 1102 | y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 1103 | }; 1104 | }; 1105 | 1106 | contextPrototype.save = function() { 1107 | var o = {}; 1108 | copyState(this, o); 1109 | this.aStack_.push(o); 1110 | this.mStack_.push(this.m_); 1111 | this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); 1112 | }; 1113 | 1114 | contextPrototype.restore = function() { 1115 | if (this.aStack_.length) { 1116 | copyState(this.aStack_.pop(), this); 1117 | this.m_ = this.mStack_.pop(); 1118 | } 1119 | }; 1120 | 1121 | function matrixIsFinite(m) { 1122 | return isFinite(m[0][0]) && isFinite(m[0][1]) && 1123 | isFinite(m[1][0]) && isFinite(m[1][1]) && 1124 | isFinite(m[2][0]) && isFinite(m[2][1]); 1125 | } 1126 | 1127 | function setM(ctx, m, updateLineScale) { 1128 | if (!matrixIsFinite(m)) { 1129 | return; 1130 | } 1131 | ctx.m_ = m; 1132 | 1133 | if (updateLineScale) { 1134 | // Get the line scale. 1135 | // Determinant of this.m_ means how much the area is enlarged by the 1136 | // transformation. So its square root can be used as a scale factor 1137 | // for width. 1138 | var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; 1139 | ctx.lineScale_ = sqrt(abs(det)); 1140 | } 1141 | } 1142 | 1143 | contextPrototype.translate = function(aX, aY) { 1144 | var m1 = [ 1145 | [1, 0, 0], 1146 | [0, 1, 0], 1147 | [aX, aY, 1] 1148 | ]; 1149 | 1150 | setM(this, matrixMultiply(m1, this.m_), false); 1151 | }; 1152 | 1153 | contextPrototype.rotate = function(aRot) { 1154 | var c = mc(aRot); 1155 | var s = ms(aRot); 1156 | 1157 | var m1 = [ 1158 | [c, s, 0], 1159 | [-s, c, 0], 1160 | [0, 0, 1] 1161 | ]; 1162 | 1163 | setM(this, matrixMultiply(m1, this.m_), false); 1164 | }; 1165 | 1166 | contextPrototype.scale = function(aX, aY) { 1167 | this.arcScaleX_ *= aX; 1168 | this.arcScaleY_ *= aY; 1169 | var m1 = [ 1170 | [aX, 0, 0], 1171 | [0, aY, 0], 1172 | [0, 0, 1] 1173 | ]; 1174 | 1175 | setM(this, matrixMultiply(m1, this.m_), true); 1176 | }; 1177 | 1178 | contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { 1179 | var m1 = [ 1180 | [m11, m12, 0], 1181 | [m21, m22, 0], 1182 | [dx, dy, 1] 1183 | ]; 1184 | 1185 | setM(this, matrixMultiply(m1, this.m_), true); 1186 | }; 1187 | 1188 | contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { 1189 | var m = [ 1190 | [m11, m12, 0], 1191 | [m21, m22, 0], 1192 | [dx, dy, 1] 1193 | ]; 1194 | 1195 | setM(this, m, true); 1196 | }; 1197 | 1198 | /** 1199 | * The text drawing function. 1200 | * The maxWidth argument isn't taken in account, since no browser supports 1201 | * it yet. 1202 | */ 1203 | contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) { 1204 | var m = this.m_, 1205 | delta = 1000, 1206 | left = 0, 1207 | right = delta, 1208 | offset = {x: 0, y: 0}, 1209 | lineStr = []; 1210 | 1211 | var fontStyle = getComputedStyle(processFontStyle(this.font), 1212 | this.element_); 1213 | 1214 | var fontStyleString = buildStyle(fontStyle); 1215 | 1216 | var elementStyle = this.element_.currentStyle; 1217 | var textAlign = this.textAlign.toLowerCase(); 1218 | switch (textAlign) { 1219 | case 'left': 1220 | case 'center': 1221 | case 'right': 1222 | break; 1223 | case 'end': 1224 | textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left'; 1225 | break; 1226 | case 'start': 1227 | textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left'; 1228 | break; 1229 | default: 1230 | textAlign = 'left'; 1231 | } 1232 | 1233 | // 1.75 is an arbitrary number, as there is no info about the text baseline 1234 | switch (this.textBaseline) { 1235 | case 'hanging': 1236 | case 'top': 1237 | offset.y = fontStyle.size / 1.75; 1238 | break; 1239 | case 'middle': 1240 | break; 1241 | default: 1242 | case null: 1243 | case 'alphabetic': 1244 | case 'ideographic': 1245 | case 'bottom': 1246 | offset.y = -fontStyle.size / 2.25; 1247 | break; 1248 | } 1249 | 1250 | switch(textAlign) { 1251 | case 'right': 1252 | left = delta; 1253 | right = 0.05; 1254 | break; 1255 | case 'center': 1256 | left = right = delta / 2; 1257 | break; 1258 | } 1259 | 1260 | var d = getCoords(this, x + offset.x, y + offset.y); 1261 | 1262 | lineStr.push(''); 1266 | 1267 | if (stroke) { 1268 | appendStroke(this, lineStr); 1269 | } else { 1270 | // TODO: Fix the min and max params. 1271 | appendFill(this, lineStr, {x: -left, y: 0}, 1272 | {x: right, y: fontStyle.size}); 1273 | } 1274 | 1275 | var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' + 1276 | m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0'; 1277 | 1278 | var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z); 1279 | 1280 | lineStr.push('', 1282 | '', 1283 | ''); 1288 | 1289 | this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); 1290 | }; 1291 | 1292 | contextPrototype.fillText = function(text, x, y, maxWidth) { 1293 | this.drawText_(text, x, y, maxWidth, false); 1294 | }; 1295 | 1296 | contextPrototype.strokeText = function(text, x, y, maxWidth) { 1297 | this.drawText_(text, x, y, maxWidth, true); 1298 | }; 1299 | 1300 | contextPrototype.measureText = function(text) { 1301 | if (!this.textMeasureEl_) { 1302 | var s = ''; 1305 | this.element_.insertAdjacentHTML('beforeEnd', s); 1306 | this.textMeasureEl_ = this.element_.lastChild; 1307 | } 1308 | var doc = this.element_.ownerDocument; 1309 | this.textMeasureEl_.innerHTML = ''; 1310 | this.textMeasureEl_.style.font = this.font; 1311 | // Don't use innerHTML or innerText because they allow markup/whitespace. 1312 | this.textMeasureEl_.appendChild(doc.createTextNode(text)); 1313 | return {width: this.textMeasureEl_.offsetWidth}; 1314 | }; 1315 | 1316 | /******** STUBS ********/ 1317 | contextPrototype.clip = function() { 1318 | // TODO: Implement 1319 | }; 1320 | 1321 | contextPrototype.arcTo = function() { 1322 | // TODO: Implement 1323 | }; 1324 | 1325 | contextPrototype.createPattern = function(image, repetition) { 1326 | return new CanvasPattern_(image, repetition); 1327 | }; 1328 | 1329 | // Gradient / Pattern Stubs 1330 | function CanvasGradient_(aType) { 1331 | this.type_ = aType; 1332 | this.x0_ = 0; 1333 | this.y0_ = 0; 1334 | this.r0_ = 0; 1335 | this.x1_ = 0; 1336 | this.y1_ = 0; 1337 | this.r1_ = 0; 1338 | this.colors_ = []; 1339 | } 1340 | 1341 | CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { 1342 | aColor = processStyle(aColor); 1343 | this.colors_.push({offset: aOffset, 1344 | color: aColor.color, 1345 | alpha: aColor.alpha}); 1346 | }; 1347 | 1348 | function CanvasPattern_(image, repetition) { 1349 | assertImageIsValid(image); 1350 | switch (repetition) { 1351 | case 'repeat': 1352 | case null: 1353 | case '': 1354 | this.repetition_ = 'repeat'; 1355 | break 1356 | case 'repeat-x': 1357 | case 'repeat-y': 1358 | case 'no-repeat': 1359 | this.repetition_ = repetition; 1360 | break; 1361 | default: 1362 | throwException('SYNTAX_ERR'); 1363 | } 1364 | 1365 | this.src_ = image.src; 1366 | this.width_ = image.width; 1367 | this.height_ = image.height; 1368 | } 1369 | 1370 | function throwException(s) { 1371 | throw new DOMException_(s); 1372 | } 1373 | 1374 | function assertImageIsValid(img) { 1375 | if (!img || img.nodeType != 1 || img.tagName != 'IMG') { 1376 | throwException('TYPE_MISMATCH_ERR'); 1377 | } 1378 | if (img.readyState != 'complete') { 1379 | throwException('INVALID_STATE_ERR'); 1380 | } 1381 | } 1382 | 1383 | function DOMException_(s) { 1384 | this.code = this[s]; 1385 | this.message = s +': DOM Exception ' + this.code; 1386 | } 1387 | var p = DOMException_.prototype = new Error; 1388 | p.INDEX_SIZE_ERR = 1; 1389 | p.DOMSTRING_SIZE_ERR = 2; 1390 | p.HIERARCHY_REQUEST_ERR = 3; 1391 | p.WRONG_DOCUMENT_ERR = 4; 1392 | p.INVALID_CHARACTER_ERR = 5; 1393 | p.NO_DATA_ALLOWED_ERR = 6; 1394 | p.NO_MODIFICATION_ALLOWED_ERR = 7; 1395 | p.NOT_FOUND_ERR = 8; 1396 | p.NOT_SUPPORTED_ERR = 9; 1397 | p.INUSE_ATTRIBUTE_ERR = 10; 1398 | p.INVALID_STATE_ERR = 11; 1399 | p.SYNTAX_ERR = 12; 1400 | p.INVALID_MODIFICATION_ERR = 13; 1401 | p.NAMESPACE_ERR = 14; 1402 | p.INVALID_ACCESS_ERR = 15; 1403 | p.VALIDATION_ERR = 16; 1404 | p.TYPE_MISMATCH_ERR = 17; 1405 | 1406 | // set up externs 1407 | G_vmlCanvasManager = G_vmlCanvasManager_; 1408 | CanvasRenderingContext2D = CanvasRenderingContext2D_; 1409 | CanvasGradient = CanvasGradient_; 1410 | CanvasPattern = CanvasPattern_; 1411 | DOMException = DOMException_; 1412 | })(); 1413 | 1414 | } // if 1415 | -------------------------------------------------------------------------------- /silverlight/excanvas.js: -------------------------------------------------------------------------------- 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 | 15 | 16 | // Known Issues: (From VML version) 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 | // * Coordsize. The width and height attribute have higher priority than the 22 | // width and height style values which isn't correct. 23 | // * Painting mode isn't implemented. 24 | // * Canvas width/height should is using content-box by default. IE in 25 | // Quirks mode will draw the canvas using border-box. Either change your 26 | // doctype to HTML5 27 | // (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) 28 | // or use Box Sizing Behavior from WebFX 29 | // (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) 30 | // * Optimize. There is always room for speed improvements. 31 | 32 | //Known Issues: Silverlight version 33 | // 34 | // * Doing a transformation during a path (ie lineTo, transform, lineTo) will 35 | // not work corerctly because the transform is done to the whole path (ie 36 | // transform, lineTo, lineTo) 37 | // * Patterns are not yet implemented. 38 | 39 | 40 | // only add this code if we do not already have a canvas implementation 41 | if (!window.CanvasRenderingContext2D) { 42 | 43 | (function () { 44 | 45 | var xamlId; 46 | 47 | var G_vmlCanvasManager_ = { 48 | init: function (opt_doc) { 49 | var doc = opt_doc || document; 50 | // Create a dummy element so that IE will allow canvas elements to be 51 | // recognized. 52 | doc.createElement('canvas'); 53 | if (/MSIE/.test(navigator.userAgent) && !window.opera) { 54 | var self = this; 55 | 56 | createXamlScriptTag(); 57 | 58 | doc.attachEvent('onreadystatechange', function () { 59 | self.init_(doc); 60 | }); 61 | } 62 | }, 63 | 64 | init_: function (doc) { 65 | // setup default css 66 | var ss = doc.createStyleSheet(); 67 | ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + 68 | // default size is 300x150 in Gecko and Opera 69 | 'text-align:left;width:300px;height:150px}' + 70 | 'canvas *{width:100%;height:100%;border:0;' + 71 | 'background:transparen;margin:0}' + 72 | 'canvas div {position:relative}' + 73 | // Place a div on top of the plugin. 74 | 'canvas div div{position:absolute;top:0;' + 75 | // needs to be "non transparent" 76 | 'filter:alpha(opacity=0);background:red}'; 77 | 78 | // find all canvas elements 79 | var els = doc.getElementsByTagName('canvas'); 80 | for (var i = 0; i < els.length; i++) { 81 | if (!els[i].getContext) { 82 | this.initElement(els[i]); 83 | } 84 | } 85 | }, 86 | 87 | 88 | /** 89 | * Public initializes a canvas element so that it can be used as canvas 90 | * element from now on. This is called automatically before the page is 91 | * loaded but if you are creating elements using createElement you need to 92 | * make sure this is called on the element. 93 | * @param {HTMLElement} el The canvas element to initialize. 94 | * @return {HTMLElement} the element that was created. 95 | */ 96 | initElement: function (el) { 97 | el.getContext = function () { 98 | if (this.context_) { 99 | return this.context_; 100 | } 101 | return this.context_ = new CanvasRenderingContext2D_(this); 102 | }; 103 | 104 | var attrs = el.attributes; 105 | if (attrs.width && attrs.width.specified) { 106 | // TODO: use runtimeStyle and coordsize 107 | // el.getContext().setWidth_(attrs.width.nodeValue); 108 | el.style.width = attrs.width.nodeValue + 'px'; 109 | } else { 110 | el.width = el.clientWidth; 111 | } 112 | if (attrs.height && attrs.height.specified) { 113 | // TODO: use runtimeStyle and coordsize 114 | // el.getContext().setHeight_(attrs.height.nodeValue); 115 | el.style.height = attrs.height.nodeValue + 'px'; 116 | } else { 117 | el.height = el.clientHeight; 118 | } 119 | 120 | // insert object tag 121 | el.innerHTML = getObjectHtml(); 122 | 123 | // do not use inline function because that will leak memory 124 | el.attachEvent('onpropertychange', onPropertyChange); 125 | return el; 126 | } 127 | }; 128 | 129 | function onPropertyChange(e) { 130 | var el = e.srcElement; 131 | 132 | switch (e.propertyName) { 133 | case 'width': 134 | el.style.width = el.attributes.width.nodeValue + 'px'; 135 | el.getContext().clearRect(); 136 | break; 137 | case 'height': 138 | el.style.height = el.attributes.height.nodeValue + 'px'; 139 | el.getContext().clearRect(); 140 | break; 141 | } 142 | } 143 | 144 | G_vmlCanvasManager_.init(); 145 | 146 | function createXamlScriptTag() { 147 | // This script tag contains the boilerplate XAML. 148 | document.write(''); 157 | // Find the id of the writtenscript file. 158 | var scripts = document.scripts; 159 | var script = scripts[scripts.length - 1]; 160 | xamlId = script.uniqueID; 161 | script.id = xamlId; 162 | } 163 | 164 | function getObjectHtml(fn) { 165 | return '
' + 166 | '' + 167 | '' + 168 | '' + 169 | '
'; 170 | } 171 | 172 | function hasSilverlight() { 173 | try { 174 | new ActiveXObject('AgControl.AgControl'); 175 | return true; 176 | } catch(_) { 177 | return false; 178 | } 179 | } 180 | 181 | // precompute "00" to "FF" 182 | var dec2hex = []; 183 | for (var i = 0; i < 16; i++) { 184 | for (var j = 0; j < 16; j++) { 185 | dec2hex[i * 16 + j] = i.toString(16) + j.toString(16); 186 | } 187 | } 188 | 189 | function createMatrixIdentity() { 190 | return [ 191 | [1, 0, 0], 192 | [0, 1, 0], 193 | [0, 0, 1] 194 | ]; 195 | } 196 | 197 | function matrixMultiply(m1, m2) { 198 | var result = createMatrixIdentity(); 199 | 200 | for (var x = 0; x < 3; x++) { 201 | for (var y = 0; y < 3; y++) { 202 | var sum = 0; 203 | 204 | for (var z = 0; z < 3; z++) { 205 | sum += m1[x][z] * m2[z][y]; 206 | } 207 | 208 | result[x][y] = sum; 209 | } 210 | } 211 | return result; 212 | } 213 | 214 | function doTransform(ctx) { 215 | transformObject(ctx, getRoot(ctx), ctx.m_); 216 | } 217 | 218 | function transformObject(ctx, obj, m) { 219 | var transform = obj.renderTransform; 220 | var matrix; 221 | if (!transform) { 222 | transform = create(ctx, ''); 223 | matrix = create(ctx, ''); 224 | transform.matrix = matrix; 225 | obj.renderTransform = transform; 226 | } else { 227 | matrix = transform.matrix; 228 | } 229 | 230 | matrix.m11 = m[0][0]; 231 | matrix.m12 = m[0][1]; 232 | matrix.m21 = m[1][0]; 233 | matrix.m22 = m[1][1]; 234 | matrix.offsetX = m[2][0]; 235 | matrix.offsetY = m[2][1]; 236 | } 237 | 238 | function copyState(o1, o2) { 239 | o2.fillStyle = o1.fillStyle; 240 | o2.lineCap = o1.lineCap; 241 | o2.lineJoin = o1.lineJoin; 242 | o2.lineWidth = o1.lineWidth; 243 | o2.miterLimit = o1.miterLimit; 244 | o2.shadowBlur = o1.shadowBlur; 245 | o2.shadowColor = o1.shadowColor; 246 | o2.shadowOffsetX = o1.shadowOffsetX; 247 | o2.shadowOffsetY = o1.shadowOffsetY; 248 | o2.strokeStyle = o1.strokeStyle; 249 | o2.globalAlpha = o1.globalAlpha; 250 | o2.arcScaleX_ = o1.arcScaleX_; 251 | o2.arcScaleY_ = o1.arcScaleY_; 252 | } 253 | 254 | // precompute "00" to "FF" 255 | var decToHex = []; 256 | for (var i = 0; i < 16; i++) { 257 | for (var j = 0; j < 16; j++) { 258 | decToHex[i * 16 + j] = i.toString(16) + j.toString(16); 259 | } 260 | } 261 | 262 | // Silverlight does not support spelling gray as grey. 263 | var colorData = { 264 | darkgrey: '#A9A9A9', 265 | darkslategrey: '#2F4F4F', 266 | dimgrey: '#696969', 267 | grey: '#808080', 268 | lightgrey: '#D3D3D3', 269 | lightslategrey: '#778899', 270 | slategrey: '#708090' 271 | }; 272 | 273 | 274 | function getRgbHslContent(styleString) { 275 | var start = styleString.indexOf('(', 3); 276 | var end = styleString.indexOf(')', start + 1); 277 | var parts = styleString.substring(start + 1, end).split(','); 278 | // add alpha if needed 279 | if (parts.length == 4 && styleString.substr(3, 1) == 'a') { 280 | alpha = +parts[3]; 281 | } else { 282 | parts[3] = 1; 283 | } 284 | return parts; 285 | } 286 | 287 | function percent(s) { 288 | return parseFloat(s) / 100; 289 | } 290 | 291 | function clamp(v, min, max) { 292 | return Math.min(max, Math.max(min, v)); 293 | } 294 | 295 | function hslToRgb(parts){ 296 | var r, g, b; 297 | h = parseFloat(parts[0]) / 360 % 360; 298 | if (h < 0) 299 | h++; 300 | s = clamp(percent(parts[1]), 0, 1); 301 | l = clamp(percent(parts[2]), 0, 1); 302 | if (s == 0) { 303 | r = g = b = l; // achromatic 304 | } else { 305 | var q = l < 0.5 ? l * (1 + s) : l + s - l * s; 306 | var p = 2 * l - q; 307 | r = hueToRgb(p, q, h + 1 / 3); 308 | g = hueToRgb(p, q, h); 309 | b = hueToRgb(p, q, h - 1 / 3); 310 | } 311 | 312 | return decToHex[Math.floor(r * 255)] + 313 | decToHex[Math.floor(g * 255)] + 314 | decToHex[Math.floor(b * 255)]; 315 | } 316 | 317 | function hueToRgb(m1, m2, h) { 318 | if (h < 0) 319 | h++; 320 | if (h > 1) 321 | h--; 322 | 323 | if (6 * h < 1) 324 | return m1 + (m2 - m1) * 6 * h; 325 | else if (2 * h < 1) 326 | return m2; 327 | else if (3 * h < 2) 328 | return m1 + (m2 - m1) * (2 / 3 - h) * 6; 329 | else 330 | return m1; 331 | } 332 | 333 | function translateColor(styleString) { 334 | var str, alpha = 1; 335 | 336 | styleString = String(styleString); 337 | if (styleString.charAt(0) == '#') { 338 | return styleString; 339 | } else if (/^rgb/.test(styleString)) { 340 | var parts = getRgbHslContent(styleString); 341 | var str = '', n; 342 | for (var i = 0; i < 3; i++) { 343 | if (parts[i].indexOf('%') != -1) { 344 | n = Math.floor(percent(parts[i]) * 255); 345 | } else { 346 | n = +parts[i]; 347 | } 348 | str += decToHex[clamp(n, 0, 255)]; 349 | } 350 | alpha = parts[3]; 351 | } else if (/^hsl/.test(styleString)) { 352 | var parts = getRgbHslContent(styleString); 353 | str = hslToRgb(parts); 354 | alpha = parts[3]; 355 | } else if (styleString in colorData) { 356 | return colorData[styleString]; 357 | } else { 358 | return styleString; 359 | } 360 | return '#' + dec2hex[Math.floor(alpha * 255)] + str; 361 | } 362 | 363 | function processLineCap(lineCap) { 364 | switch (lineCap) { 365 | case 'butt': 366 | return 'flat'; 367 | case 'round': 368 | return 'round'; 369 | case 'square': 370 | default: 371 | return 'square'; 372 | } 373 | } 374 | 375 | function getRoot(ctx) { 376 | return ctx.canvas.firstChild.firstChild.content.findName('root'); 377 | } 378 | 379 | function create(ctx, s, opt_args) { 380 | if (opt_args) { 381 | s = s.replace(/\%(\d+)/g, function(match, index) { 382 | return opt_args[+index - 1]; 383 | }); 384 | } 385 | 386 | try { 387 | return ctx.canvas.firstChild.firstChild.content.createFromXaml(s); 388 | } catch (ex) { 389 | throw Error('Could not create XAML from: ' + s); 390 | } 391 | } 392 | 393 | function drawShape(ctx, s, opt_args) { 394 | var canvas = ctx.lastCanvas_ || create(ctx, ''); 395 | var shape = create(ctx, s, opt_args); 396 | canvas.children.add(shape); 397 | transformObject(ctx, canvas, ctx.m_); 398 | if (!ctx.lastCanvas_) { 399 | getRoot(ctx).children.add(canvas); 400 | ctx.lastCanvas_ = canvas; 401 | } 402 | return shape; 403 | } 404 | 405 | function createBrushObject(ctx, value) { 406 | if (value instanceof CanvasGradient_) { 407 | return value.createBrush_(ctx); 408 | } else if (value instanceof CanvasPattern_) { 409 | throw Error('Not implemented'); 410 | } else { 411 | return create(ctx, '', 412 | [translateColor(value)]); 413 | } 414 | } 415 | 416 | /** 417 | * This class implements CanvasRenderingContext2D interface as described by 418 | * the WHATWG. 419 | * @param {HTMLElement} surfaceElement The element that the 2D context should 420 | * be associated with 421 | */ 422 | function CanvasRenderingContext2D_(surfaceElement) { 423 | this.m_ = createMatrixIdentity(); 424 | this.lastCanvas_ = null; 425 | 426 | this.mStack_ = []; 427 | this.aStack_ = []; 428 | this.currentPath_ = []; 429 | 430 | // Canvas context properties 431 | this.strokeStyle = '#000'; 432 | this.fillStyle = '#000'; 433 | 434 | this.lineWidth = 1; 435 | this.lineJoin = 'miter'; 436 | this.lineCap = 'butt'; 437 | this.miterLimit = 10; 438 | this.globalAlpha = 1; 439 | this.canvas = surfaceElement; 440 | }; 441 | 442 | 443 | var contextPrototype = CanvasRenderingContext2D_.prototype; 444 | 445 | contextPrototype.clearRect = function() { 446 | var root = getRoot(this); 447 | root.children.clear(); 448 | 449 | // TODO: Implement 450 | this.currentPath_ = []; 451 | this.lastCanvas_ = null; 452 | 453 | }; 454 | 455 | contextPrototype.beginPath = function() { 456 | // TODO: Branch current matrix so that save/restore has no effect 457 | // as per safari docs. 458 | 459 | this.currentPath_ = []; 460 | }; 461 | 462 | contextPrototype.moveTo = function(aX, aY) { 463 | this.currentPath_.push('M' + aX + ',' + aY); 464 | }; 465 | 466 | contextPrototype.lineTo = function(aX, aY) { 467 | if (this.currentPath_.length == 0) return; 468 | this.currentPath_.push('L' + aX + ',' + aY); 469 | }; 470 | 471 | contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, 472 | aCP2x, aCP2y, 473 | aX, aY) { 474 | if (this.currentPath_.length == 0) return; 475 | this.currentPath_.push('C' + aCP1x + ',' + aCP1y + ' ' + 476 | aCP2x + ',' + aCP2y + ' ' + 477 | aX + ' ' + aY); 478 | }; 479 | 480 | contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { 481 | if (this.currentPath_.length == 0) return; 482 | this.currentPath_.push('Q' + aCPx + ',' + aCPy + ' ' + 483 | aX + ',' + aY); 484 | }; 485 | 486 | contextPrototype.arcTo = function(x1, y1, x2, y2, radius) { 487 | if (this.currentPath_.length == 0) return; 488 | // TODO: Implement 489 | }; 490 | 491 | contextPrototype.arc = function(aX, aY, aRadius, 492 | aStartAngle, aEndAngle, aClockwise) { 493 | var deltaAngle = Math.abs(aStartAngle - aEndAngle); 494 | // If start and stop are the same WebKit and Moz does nothing 495 | if (aStartAngle == aEndAngle) { 496 | // different browsers behave differently here so we do the easiest thing 497 | return; 498 | } 499 | 500 | var endX = aX + aRadius * Math.cos(aEndAngle); 501 | var endY = aY + aRadius * Math.sin(aEndAngle); 502 | 503 | if (deltaAngle >= 2 * Math.PI) { 504 | // if larger than 2PI 505 | this.arc(aX, aY, aRadius, aStartAngle, aStartAngle + Math.PI, aClockwise); 506 | this.arc(aX, aY, aRadius, aStartAngle + Math.PI, 507 | aStartAngle + 2 * Math.PI, aClockwise); 508 | // now move to end point 509 | this.moveTo(endX, endY); 510 | return; 511 | } 512 | 513 | var startX = aX + aRadius * Math.cos(aStartAngle); 514 | var startY = aY + aRadius * Math.sin(aStartAngle); 515 | var rotationAngle = deltaAngle * 180 / Math.PI; // sign, abs? 516 | var sweepDirection = aClockwise ? 0 : 1; 517 | var isLargeArc = rotationAngle >= 180 == Boolean(aClockwise) ? 0 : 1; 518 | 519 | if (this.currentPath_.length != 0) { 520 | // add line to start point 521 | this.lineTo(startX, startY); 522 | } else { 523 | this.moveTo(startX, startY); 524 | } 525 | 526 | this.currentPath_.push('A' + aRadius + ',' + aRadius + ' ' + 527 | rotationAngle + ' ' + 528 | isLargeArc + ' ' + 529 | sweepDirection + ' ' + 530 | endX + ',' + endY); 531 | }; 532 | 533 | contextPrototype.rect = function(aX, aY, aWidth, aHeight) { 534 | this.moveTo(aX, aY); 535 | this.lineTo(aX + aWidth, aY); 536 | this.lineTo(aX + aWidth, aY + aHeight); 537 | this.lineTo(aX, aY + aHeight); 538 | this.closePath(); 539 | }; 540 | 541 | contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { 542 | // Will destroy any existing path (same as FF behaviour) 543 | this.beginPath(); 544 | this.moveTo(aX, aY); 545 | this.lineTo(aX + aWidth, aY); 546 | this.lineTo(aX + aWidth, aY + aHeight); 547 | this.lineTo(aX, aY + aHeight); 548 | this.closePath(); 549 | this.stroke(); 550 | this.currentPath_ = []; 551 | }; 552 | 553 | contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { 554 | // Will destroy any existing path (same as FF behaviour) 555 | this.beginPath(); 556 | this.moveTo(aX, aY); 557 | this.lineTo(aX + aWidth, aY); 558 | this.lineTo(aX + aWidth, aY + aHeight); 559 | this.lineTo(aX, aY + aHeight); 560 | this.closePath(); 561 | this.fill(); 562 | this.currentPath_ = []; 563 | }; 564 | 565 | contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { 566 | return new LinearCanvasGradient_(aX0, aY0, aX1, aY1); 567 | }; 568 | 569 | contextPrototype.createRadialGradient = function(x0, y0, 570 | r0, x1, 571 | y1, r1) { 572 | return new RadialCanvasGradient_(x0, y0, r0, x1, y1, r1); 573 | }; 574 | 575 | contextPrototype.drawImage = function (image, var_args) { 576 | var dx, dy, dw, dh, sx, sy, sw, sh; 577 | 578 | // For Silverlight we don't need to get the size of the image since 579 | // Silverlight uses the image original dimension if not provided. 580 | 581 | if (arguments.length == 3) { 582 | dx = arguments[1]; 583 | dy = arguments[2]; 584 | // Keep sx, sy, sw, dw, sh and dh undefined 585 | } else if (arguments.length == 5) { 586 | dx = arguments[1]; 587 | dy = arguments[2]; 588 | dw = arguments[3]; 589 | dh = arguments[4]; 590 | // Keep sx, sy, sw and sh undefined 591 | } else if (arguments.length == 9) { 592 | sx = arguments[1]; 593 | sy = arguments[2]; 594 | sw = arguments[3]; 595 | sh = arguments[4]; 596 | dx = arguments[5]; 597 | dy = arguments[6]; 598 | dw = arguments[7]; 599 | dh = arguments[8]; 600 | } else { 601 | throw Error('Invalid number of arguments'); 602 | } 603 | 604 | var slImage; 605 | 606 | // If we have a source rect we need to clip the image. 607 | if (arguments.length == 9) { 608 | slImage = drawShape(this, '', [image.src]); 609 | 610 | var clipRect = create(this, 611 | '', [sx, sy, sw, sh]); 612 | slImage.clip = clipRect; 613 | 614 | var m = createMatrixIdentity(); 615 | 616 | // translate to 0,0 617 | m[2][0] = -sx; 618 | m[2][1] = -sy; 619 | 620 | // scale 621 | var m2 = createMatrixIdentity(); 622 | m2[0][0] = dw / sw; 623 | m2[1][1] = dh / sh; 624 | 625 | m = matrixMultiply(m, m2); 626 | 627 | // translate to destination 628 | m[2][0] += dx; 629 | m[2][1] += dy; 630 | 631 | transformObject(this, slImage, m); 632 | 633 | } else { 634 | slImage = drawShape(this, 635 | '', 636 | [image.src, dx, dy]); 637 | if (dw != undefined || dh != undefined) { 638 | slImage.width = dw; 639 | slImage.height = dh; 640 | slImage.stretch = 'fill'; 641 | } 642 | } 643 | }; 644 | 645 | contextPrototype.stroke = function() { 646 | if (this.currentPath_.length == 0) return; 647 | var path = drawShape(this, '', 648 | [this.currentPath_.join(' ')]); 649 | path.stroke = createBrushObject(this, this.strokeStyle); 650 | path.opacity = this.globalAlpha; 651 | path.strokeThickness = this.lineWidth; 652 | path.strokeMiterLimit = this.miterLimit; 653 | path.strokeLineJoin = this.lineJoin; 654 | // Canvas does not differentiate start from end 655 | path.strokeEndLineCap = path.strokeStartLineCap = 656 | processLineCap(this.lineCap); 657 | }; 658 | 659 | contextPrototype.fill = function() { 660 | if (this.currentPath_.length == 0) return; 661 | var path = drawShape(this, '', 662 | [this.currentPath_.join(' ')]); 663 | // The spec says to use non zero but Silverlight uses EvenOdd by defaul 664 | path.data.fillRule = 'NonZero'; 665 | path.fill = createBrushObject(this, this.fillStyle); 666 | path.fill.opacity = this.globalAlpha; 667 | // TODO: What about even-odd etc? 668 | }; 669 | 670 | contextPrototype.closePath = function() { 671 | this.currentPath_.push('z'); 672 | }; 673 | 674 | /** 675 | * Sets the transformation matrix and marks things as dirty 676 | */ 677 | function setM(self, m) { 678 | self.m_ = m; 679 | self.lastCanvas_ = null; 680 | }; 681 | 682 | contextPrototype.save = function() { 683 | var o = {}; 684 | copyState(this, o); 685 | this.aStack_.push(o); 686 | this.mStack_.push(this.m_); 687 | setM(this, matrixMultiply(createMatrixIdentity(), this.m_)); 688 | }; 689 | 690 | contextPrototype.restore = function() { 691 | if (this.aStack_.length) { 692 | copyState(this.aStack_.pop(), this); 693 | this.m_ = this.mStack_.pop(); 694 | } 695 | }; 696 | 697 | contextPrototype.translate = function(aX, aY) { 698 | var m1 = [ 699 | [1, 0, 0], 700 | [0, 1, 0], 701 | [aX, aY, 1] 702 | ]; 703 | 704 | setM(this, matrixMultiply(m1, this.m_)); 705 | }; 706 | 707 | contextPrototype.rotate = function(aRot) { 708 | var c = Math.cos(aRot); 709 | var s = Math.sin(aRot); 710 | 711 | var m1 = [ 712 | [c, s, 0], 713 | [-s, c, 0], 714 | [0, 0, 1] 715 | ]; 716 | 717 | setM(this, matrixMultiply(m1, this.m_)); 718 | }; 719 | 720 | contextPrototype.scale = function(aX, aY) { 721 | var m1 = [ 722 | [aX, 0, 0], 723 | [0, aY, 0], 724 | [0, 0, 1] 725 | ]; 726 | 727 | setM(this, matrixMultiply(m1, this.m_)); 728 | }; 729 | 730 | contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { 731 | var m1 = [ 732 | [m11, m12, 0], 733 | [m21, m22, 0], 734 | [ dx, dy, 1] 735 | ]; 736 | 737 | setM(this, matrixMultiply(m1, this.m_)); 738 | }; 739 | 740 | contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { 741 | setM(this, [ 742 | [m11, m12, 0], 743 | [m21, m22, 0], 744 | [ dx, dy, 1], 745 | ]); 746 | }; 747 | 748 | contextPrototype.clip = function() { 749 | if (this.currentPath_.length) { 750 | var clip = this.currentPath_.join(' '); 751 | var canvas = create(this, '', 752 | [getRoot(this).width, getRoot(this).height, clip]); 753 | var parent = this.lastCanvas_ || getRoot(this); 754 | 755 | parent.children.add(canvas); 756 | this.lastCanvas_ = canvas; 757 | } 758 | }; 759 | 760 | contextPrototype.createPattern = function() { 761 | return new CanvasPattern_; 762 | }; 763 | 764 | // Gradient / Pattern Stubs 765 | function CanvasGradient_() { 766 | this.colors_ = []; 767 | } 768 | 769 | CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { 770 | aColor = translateColor(aColor); 771 | this.colors_.push({offset: aOffset, color: aColor}); 772 | }; 773 | 774 | CanvasGradient_.prototype.createStops_ = function(ctx, brushObj, colors) { 775 | var gradientStopCollection = brushObj.gradientStops; 776 | for (var i = 0, c; c = colors[i]; i++) { 777 | var color = translateColor(c.color); 778 | gradientStopCollection.add(create(ctx, 779 | '', [color, c.offset])); 780 | } 781 | }; 782 | 783 | function LinearCanvasGradient_(x0, y0, x1, y1) { 784 | CanvasGradient_.call(this); 785 | this.x0_ = x0; 786 | this.y0_ = y0; 787 | this.x1_ = x1; 788 | this.y1_ = y1; 789 | } 790 | LinearCanvasGradient_.prototype = new CanvasGradient_; 791 | 792 | LinearCanvasGradient_.prototype.createBrush_ = function(ctx) { 793 | var brushObj = create(ctx, '', 795 | [this.x0_, this.y0_, this.x1_, this.y1_]); 796 | this.createStops_(ctx, brushObj, this.colors_); 797 | return brushObj; 798 | }; 799 | 800 | function isNanOrInfinite(v) { 801 | return isNaN(v) || !isFinite(v); 802 | } 803 | 804 | function RadialCanvasGradient_(x0, y0, r0, x1, y1, r1) { 805 | if (r0 < 0 || r1 < 0 || isNanOrInfinite(x0) || isNanOrInfinite(y0) || 806 | isNanOrInfinite(x1) || isNanOrInfinite(y1)) { 807 | // IE does not support DOMException so this is as close as we get. 808 | var error = Error('DOMException.INDEX_SIZE_ERR'); 809 | error.code = 1; 810 | throw error; 811 | } 812 | 813 | CanvasGradient_.call(this); 814 | this.x0_ = x0; 815 | this.y0_ = y0; 816 | this.r0_ = r0; 817 | this.x1_ = x1; 818 | this.y1_ = y1; 819 | this.r1_ = r1; 820 | } 821 | RadialCanvasGradient_.prototype = new CanvasGradient_; 822 | 823 | CanvasGradient_.prototype.createBrush_ = function(ctx) { 824 | if (this.x0_ == this.x1_ && this.y0_ == this.y1_ && this.r0_ == this.r1_) { 825 | return null; 826 | } 827 | 828 | var radius = Math.max(this.r0_, this.r1_); 829 | var minRadius = Math.min(this.r0_, this.r1_); 830 | var brushObj = create(ctx, '', 833 | [this.x0_, this.y0_, this.x1_, this.y1_, radius]); 834 | 835 | var colors = this.colors_.concat(); 836 | 837 | if (this.r1_ < this.r0_) { 838 | // reverse color stop array 839 | colors.reverse(); 840 | for (var i = 0, c; c = colors[i]; i++) { 841 | c.offset = 1 - c.offset; 842 | } 843 | } 844 | 845 | // sort the color stops 846 | colors.sort(function(c1, c2) { 847 | return c1.offset - c2.offset; 848 | }); 849 | 850 | if (minRadius > 0) { 851 | // We need to adjust the color stops since SL always have the inner radius 852 | // at (0, 0) so we change the stops in case the min radius is not 0. 853 | for (var i = 0, c; c = colors[i]; i++) { 854 | c.offset = minRadius / radius + (radius - minRadius) / radius * c.offset; 855 | } 856 | } 857 | 858 | this.createStops_(ctx, brushObj, colors); 859 | return brushObj; 860 | }; 861 | 862 | function CanvasPattern_() {} 863 | 864 | // set up externs 865 | G_vmlCanvasManager = G_vmlCanvasManager_; 866 | CanvasRenderingContext2D = CanvasRenderingContext2D_; 867 | CanvasGradient = CanvasGradient_; 868 | CanvasPattern = CanvasPattern_; 869 | 870 | })(); 871 | 872 | } // if 873 | -------------------------------------------------------------------------------- /testcases/arc.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Arc Test 5 | 12 | 13 | 40 | 41 | 42 | 43 | 44 | 45 |

This tests that drawing arches work in the same way in different 46 | browsers.

47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /testcases/clearpath.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Clear path Test 5 | 12 | 13 | 40 | 41 | 42 | 43 | 44 | 45 |

This tests the clearing of the path. You should only see a diamond shape 46 | above.

47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /testcases/colors.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Color Test 5 | 13 | 14 | 261 | 262 | 263 | 264 | 265 | 266 | 267 |
268 | 269 | 270 | 271 | 272 | 273 | -------------------------------------------------------------------------------- /testcases/draw-image-flip.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Scale and translate image test 5 | 12 | 13 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /testcases/drawimage.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Overflow Test 5 | 12 | 13 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /testcases/gradient.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Gradient Test 5 | 12 | 13 | 31 | 32 | 33 | 34 | 35 | 36 |

This tests gradients

37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /testcases/gradient2.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Gradient Test 5 | 13 | 14 | 34 | 35 | 36 | 37 | 38 | 39 |

This tests gradients

40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /testcases/linewidth.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Line Width Test 5 | 12 | 13 | 38 | 39 | 40 | 41 | 42 | 43 |

This tests that lines work in the same way in different browsers when you are 44 | using sub pixel coordinates.

45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /testcases/overflow.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Overflow Test 5 | 12 | 13 | 29 | 30 | 31 | 32 | 33 | 34 |

This tests if content gets cropped if painting outside the canvas.

35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /testcases/overlay.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Overlay animation 5 | 8 | 9 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /testcases/pattern.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Pattern Test 5 | 12 | 13 | 33 | 34 | 35 | 36 | 37 | 38 |

This tests patterns

39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /testcases/pattern.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arv/ExplorerCanvas/44ac99ffc23b665c94a56b365d1d98ffa567e42c/testcases/pattern.jpg -------------------------------------------------------------------------------- /testcases/quadraticcurve.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Quadratic Curve Test 5 | 12 | 13 | 47 | 48 | 49 | 50 | 51 | 52 |

This tests that drawing quadratic curves work in the same way in different 53 | browsers.

54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /testcases/resizing.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | ExplorerCanvas Text Case 4 | 5 | 56 | 61 | 62 | 63 | Fallback content markup 64 | 65 | 66 | -------------------------------------------------------------------------------- /testcases/saverestorepath.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Save/restore path Test 5 | 12 | 13 | 39 | 40 | 41 | 42 | 43 | 44 |

This tests ensures that save/restore does not do anything to the current 45 | path. You should see a diamond shape above.

46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /testcases/stroke-scale-rotate.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Stroke Scale 5 | 16 | 17 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /testcases/stroke-should-not-close-path.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 12 | 13 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /testcases/text.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Text Test 5 | 9 | 10 | 70 | 71 | 72 | 73 | 74 | 75 |
76 |
77 |
78 |
79 |
83 | 84 | --------------------------------------------------------------------------------