1/*!! 2 * Canvas 2 Svg v1.0.19 3 * A low level canvas to SVG converter. Uses a mock canvas context to build an SVG document. 4 * 5 * Licensed under the MIT license: 6 * http://www.opensource.org/licenses/mit-license.php 7 * 8 * Author: 9 * Kerry Liu 10 * 11 * Copyright (c) 2014 Gliffy Inc. 12 */ 13 14;(function () { 15 "use strict"; 16 17 var STYLES, ctx, CanvasGradient, CanvasPattern, namedEntities; 18 19 //helper function to format a string 20 function format(str, args) { 21 var keys = Object.keys(args), i; 22 for (i=0; i<keys.length; i++) { 23 str = str.replace(new RegExp("\\{" + keys[i] + "\\}", "gi"), args[keys[i]]); 24 } 25 return str; 26 } 27 28 //helper function that generates a random string 29 function randomString(holder) { 30 var chars, randomstring, i; 31 if (!holder) { 32 throw new Error("cannot create a random attribute name for an undefined object"); 33 } 34 chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"; 35 randomstring = ""; 36 do { 37 randomstring = ""; 38 for (i = 0; i < 12; i++) { 39 randomstring += chars[Math.floor(Math.random() * chars.length)]; 40 } 41 } while (holder[randomstring]); 42 return randomstring; 43 } 44 45 //helper function to map named to numbered entities 46 function createNamedToNumberedLookup(items, radix) { 47 var i, entity, lookup = {}, base10, base16; 48 items = items.split(','); 49 radix = radix || 10; 50 // Map from named to numbered entities. 51 for (i = 0; i < items.length; i += 2) { 52 entity = '&' + items[i + 1] + ';'; 53 base10 = parseInt(items[i], radix); 54 lookup[entity] = '&#'+base10+';'; 55 } 56 //FF and IE need to create a regex from hex values ie == \xa0 57 lookup["\\xa0"] = ' '; 58 return lookup; 59 } 60 61 //helper function to map canvas-textAlign to svg-textAnchor 62 function getTextAnchor(textAlign) { 63 //TODO: support rtl languages 64 var mapping = {"left":"start", "right":"end", "center":"middle", "start":"start", "end":"end"}; 65 return mapping[textAlign] || mapping.start; 66 } 67 68 //helper function to map canvas-textBaseline to svg-dominantBaseline 69 function getDominantBaseline(textBaseline) { 70 //INFO: not supported in all browsers 71 var mapping = {"alphabetic": "alphabetic", "hanging": "hanging", "top":"text-before-edge", "bottom":"text-after-edge", "middle":"central"}; 72 return mapping[textBaseline] || mapping.alphabetic; 73 } 74 75 // Unpack entities lookup where the numbers are in radix 32 to reduce the size 76 // entity mapping courtesy of tinymce 77 namedEntities = createNamedToNumberedLookup( 78 '50,nbsp,51,iexcl,52,cent,53,pound,54,curren,55,yen,56,brvbar,57,sect,58,uml,59,copy,' + 79 '5a,ordf,5b,laquo,5c,not,5d,shy,5e,reg,5f,macr,5g,deg,5h,plusmn,5i,sup2,5j,sup3,5k,acute,' + 80 '5l,micro,5m,para,5n,middot,5o,cedil,5p,sup1,5q,ordm,5r,raquo,5s,frac14,5t,frac12,5u,frac34,' + 81 '5v,iquest,60,Agrave,61,Aacute,62,Acirc,63,Atilde,64,Auml,65,Aring,66,AElig,67,Ccedil,' + 82 '68,Egrave,69,Eacute,6a,Ecirc,6b,Euml,6c,Igrave,6d,Iacute,6e,Icirc,6f,Iuml,6g,ETH,6h,Ntilde,' + 83 '6i,Ograve,6j,Oacute,6k,Ocirc,6l,Otilde,6m,Ouml,6n,times,6o,Oslash,6p,Ugrave,6q,Uacute,' + 84 '6r,Ucirc,6s,Uuml,6t,Yacute,6u,THORN,6v,szlig,70,agrave,71,aacute,72,acirc,73,atilde,74,auml,' + 85 '75,aring,76,aelig,77,ccedil,78,egrave,79,eacute,7a,ecirc,7b,euml,7c,igrave,7d,iacute,7e,icirc,' + 86 '7f,iuml,7g,eth,7h,ntilde,7i,ograve,7j,oacute,7k,ocirc,7l,otilde,7m,ouml,7n,divide,7o,oslash,' + 87 '7p,ugrave,7q,uacute,7r,ucirc,7s,uuml,7t,yacute,7u,thorn,7v,yuml,ci,fnof,sh,Alpha,si,Beta,' + 88 'sj,Gamma,sk,Delta,sl,Epsilon,sm,Zeta,sn,Eta,so,Theta,sp,Iota,sq,Kappa,sr,Lambda,ss,Mu,' + 89 'st,Nu,su,Xi,sv,Omicron,t0,Pi,t1,Rho,t3,Sigma,t4,Tau,t5,Upsilon,t6,Phi,t7,Chi,t8,Psi,' + 90 't9,Omega,th,alpha,ti,beta,tj,gamma,tk,delta,tl,epsilon,tm,zeta,tn,eta,to,theta,tp,iota,' + 91 'tq,kappa,tr,lambda,ts,mu,tt,nu,tu,xi,tv,omicron,u0,pi,u1,rho,u2,sigmaf,u3,sigma,u4,tau,' + 92 'u5,upsilon,u6,phi,u7,chi,u8,psi,u9,omega,uh,thetasym,ui,upsih,um,piv,812,bull,816,hellip,' + 93 '81i,prime,81j,Prime,81u,oline,824,frasl,88o,weierp,88h,image,88s,real,892,trade,89l,alefsym,' + 94 '8cg,larr,8ch,uarr,8ci,rarr,8cj,darr,8ck,harr,8dl,crarr,8eg,lArr,8eh,uArr,8ei,rArr,8ej,dArr,' + 95 '8ek,hArr,8g0,forall,8g2,part,8g3,exist,8g5,empty,8g7,nabla,8g8,isin,8g9,notin,8gb,ni,8gf,prod,' + 96 '8gh,sum,8gi,minus,8gn,lowast,8gq,radic,8gt,prop,8gu,infin,8h0,ang,8h7,and,8h8,or,8h9,cap,8ha,cup,' + 97 '8hb,int,8hk,there4,8hs,sim,8i5,cong,8i8,asymp,8j0,ne,8j1,equiv,8j4,le,8j5,ge,8k2,sub,8k3,sup,8
97k4,' + 98 'nsub,8k6,sube,8k7,supe,8kl,oplus,8kn,otimes,8l5,perp,8m5,sdot,8o8,lceil,8o9,rceil,8oa,lfloor,8ob,' + 99 'rfloor,8p9,lang,8pa,rang,9ea,loz,9j0,spades,9j3,clubs,9j5,hearts,9j6,diams,ai,OElig,aj,oelig,b0,' + 100 'Scaron,b1,scaron,bo,Yuml,m6,circ,ms,tilde,802,ensp,803,emsp,809,thinsp,80c,zwnj,80d,zwj,80e,lrm,' + 101 '80f,rlm,80j,ndash,80k,mdash,80o,lsquo,80p,rsquo,80q,sbquo,80s,ldquo,80t,rdquo,80u,bdquo,810,dagger,' + 102 '811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro', 32); 103 104 105 //Some basic mappings for attributes and default values. 106 STYLES = { 107 "strokeStyle":{ 108 svgAttr : "stroke", //corresponding svg attribute 109 canvas : "#000000", //canvas default 110 svg : "none", //svg default 111 apply : "stroke" //apply on stroke() or fill() 112 }, 113 "fillStyle":{ 114 svgAttr : "fill", 115 canvas : "#000000", 116 svg : null, //svg default is black, but we need to special case this to handle canvas stroke without fill 117 apply : "fill" 118 }, 119 "lineCap":{ 120 svgAttr : "stroke-linecap", 121 canvas : "butt", 122 svg : "butt", 123 apply : "stroke" 124 }, 125 "lineJoin":{ 126 svgAttr : "stroke-linejoin", 127 canvas : "miter", 128 svg : "miter", 129 apply : "stroke" 130 }, 131 "miterLimit":{ 132 svgAttr : "stroke-miterlimit", 133 canvas : 10, 134 svg : 4, 135 apply : "stroke" 136 }, 137 "lineWidth":{ 138 svgAttr : "stroke-width", 139 canvas : 1, 140 svg : 1, 141 apply : "stroke" 142 }, 143 "globalAlpha": { 144 svgAttr : "opacity", 145 canvas : 1, 146 svg : 1, 147 apply : "fill stroke" 148 }, 149 "font":{ 150 //font converts to multiple svg attributes, there is custom logic for this 151 canvas : "10px sans-serif" 152 }, 153 "shadowColor":{ 154 canvas : "#000000" 155 }, 156 "shadowOffsetX":{ 157 canvas : 0 158 }, 159 "shadowOffsetY":{ 160 canvas : 0 161 }, 162 "shadowBlur":{ 163 canvas : 0 164 }, 165 "textAlign":{ 166 canvas : "start" 167 }, 168 "textBaseline":{ 169 canvas : "alphabetic" 170 }, 171 "lineDash" : { 172 svgAttr : "stroke-dasharray", 173 canvas : [], 174 svg : null, 175 apply : "stroke" 176 } 177 }; 178 179 /** 180 * 181 * @param gradientNode - reference to the gradient 182 * @constructor 183 */ 184 CanvasGradient = function (gradientNode, ctx) { 185 this.__root = gradientNode; 186 this.__ctx = ctx; 187 }; 188 189 /** 190 * Adds a color stop to the gradient root 191 */ 192 CanvasGradient.prototype.addColorStop = function (offset, color) { 193 var stop = this.__ctx.__createElement("stop"), regex, matches; 194 stop.setAttribute("offset", offset); 195 if (color.indexOf("rgba") !== -1) { 196 //separate alpha value, since webkit can't handle it 197 regex = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?\.?\d*)\s*\)/gi; 198 matches = regex.exec(color); 199 stop.setAttribute("stop-color", format("rgb({r},{g},{b})", {r:matches[1], g:matches[2], b:matches[3]})); 200 stop.setAttribute("stop-opacity", matches[4]); 201 } else { 202 stop.setAttribute("stop-color", color); 203 } 204 this.__root.appendChild(stop); 205 }; 206 207 CanvasPattern = function (pattern, ctx) { 208 this.__root = pattern; 209 this.__ctx = ctx; 210 }; 211 212 /** 213 * The mock canvas context 214 * @param o - options include: 215 * ctx - existing Context2D to wrap around 216 * width - width of your canvas (defaults to 500) 217 * height - height of your canvas (defaults to 500) 218 * enableMirroring - enables canvas mirroring (get image data) (defaults to false) 219 * document - the document object (defaults to the current document) 220 */ 221 ctx = function (o) { 222 var defaultOptions = { width:500, height:500, enableMirroring : false}, options; 223
224 //keep support for this way of calling C2S: new C2S(width,height) 225 if (arguments.length > 1) { 226 options = defaultOptions; 227 options.width = arguments[0]; 228 options.height = arguments[1]; 229 } else if ( !o ) { 230 options = defaultOptions; 231 } else { 232 options = o; 233 } 234 235 if (!(this instanceof ctx)) { 236 //did someone call this without new? 237 return new ctx(options); 238 } 239 240 //setup options 241 this.width = options.width || defaultOptions.width; 242 this.height = options.height || defaultOptions.height; 243 this.enableMirroring = options.enableMirroring !== undefined ? options.enableMirroring : defaultOptions.enableMirroring; 244 245 this.canvas = this; ///point back to this instance! 246 this.__document = options.document || document; 247 248 // allow passing in an existing context to wrap around 249 // if a context is passed in, we know a canvas already exist 250 if (options.ctx) { 251 this.__ctx = options.ctx; 252 } else { 253 this.__canvas = this.__document.createElement("canvas"); 254 this.__ctx = this.__canvas.getContext("2d"); 255 } 256 257 this.__setDefaultStyles(); 258 this.__stack = [this.__getStyleState()]; 259 this.__groupStack = []; 260 261 //the root svg element 262 this.__root = this.__document.createElementNS("http://www.w3.org/2000/svg", "svg"); 263 this.__root.setAttribute("version", 1.1); 264 this.__root.setAttribute("xmlns", "http://www.w3.org/2000/svg"); 265 this.__root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink"); 266 this.__root.setAttribute("width", this.width); 267 this.__root.setAttribute("height", this.height); 268 269 //make sure we don't generate the same ids in defs 270 this.__ids = {}; 271 272 //defs tag 273 this.__defs = this.__document.createElementNS("http://www.w3.org/2000/svg", "def
273s"); 274 this.__root.appendChild(this.__defs); 275 276 //also add a group child. the svg element can't use the transform attribute 277 this.__currentElement = this.__document.createElementNS("http://www.w3.org/2000/svg", "g"); 278 this.__root.appendChild(this.__currentElement); 279 }; 280 281 282 /** 283 * Creates the specified svg element 284 * @private 285 */ 286 ctx.prototype.__createElement = function (elementName, properties, resetFill) { 287 if (typeof properties === "undefined") { 288 properties = {}; 289 } 290 291 var element = this.__document.createElementNS("http://www.w3.org/2000/svg", elementName), 292 keys = Object.keys(properties), i, key; 293 if (resetFill) { 294 //if fill or stroke is not specified, the svg element should not display. By default SVG's fill is black. 295 element.setAttribute("fill", "none"); 296 element.setAttribute("stroke", "none"); 297 } 298 for (i=0; i<keys.length; i++) { 299 key = keys[i]; 300 element.setAttribute(key, properties[key]); 301 } 302 return element; 303 }; 304 305 /** 306 * Applies default canvas styles to the context 307 * @private 308 */ 309 ctx.prototype.__setDefaultStyles = function () { 310 //default 2d canvas context properties see:http://www.w3.org/TR/2dcontext/ 311 var keys = Object.keys(STYLES), i, key; 312 for (i=0; i<keys.length; i++) { 313 key = keys[i]; 314 this[key] = STYLES[key].canvas; 315 } 316 }; 317 318 /** 319 * Applies styles on restore 320 * @param styleState 321 * @private 322 */ 323 ctx.prototype.__applyStyleState = function (styleState) { 324 var keys = Object.keys(styleState), i, key; 325 for (i=0; i<keys.length; i++) { 326 key = keys[i]; 327 this[key] = styleState[key]; 328 } 329 }; 330 331 /** 332 * Gets the current style state 333 * @return {Object} 334 * @private 335 */ 336 ctx.prototype.__getStyleState = function () { 337 var i, styleState = {}, keys = Object.keys(STYLES), key; 338 for (i=0; i<keys.length; i++) { 339 key = keys[i]; 340 styleState[key] = this[key]; 341 } 342 return styleState; 343 }; 344 345 /** 346 * Apples the current styles to the current SVG element. On "ctx.fill" or "ctx.stroke" 347 * @param type 348 * @private 349 */ 350 ctx.prototype.__applyStyleToCurrentElement = function (type) { 351 var currentElement = this.__currentElement; 352 var currentStyleGroup = this.__currentElementsToStyle; 353 if (currentStyleGroup) { 354 currentElement.setAttribute(type, ""); 355 currentElement = currentStyleGroup.element; 356 currentStyleGroup.children.forEach(function (node) { 357 node.setAttribute(type, ""); 358 }) 359 } 360 361 var keys = Object.keys(STYLES), i, style, value, id, regex, matches; 362 for (i = 0; i < keys.length; i++) { 363 style = STYLES[keys[i]]; 364 value = this[keys[i]]; 365 if (style.apply) { 366 //is this a gradient or pattern? 367 if (value instanceof CanvasPattern) { 368 //pattern 369 if (value.__ctx) { 370 //copy over defs 371 while(value.__ctx.__defs.childNodes.length) { 372 id = value.__ctx.__defs.childNodes[0].getAttribute("id"); 373 this.__ids[id] = id; 374 this.__defs.appendChild(value.__ctx.__defs.childNodes[0]); 375 } 376 } 377 currentElement.setAttribute(style.apply, format("url(#{id})", {id:value.__root.getAttribute("id")})); 378 } 379 else if (value instanceof CanvasGradient) { 380 //gradient 381 currentElement.setAttribute(style.apply, format("url(#{id})", {id:value.__root.getAttribute("id")})); 382 } else if (style.apply.indexOf(type)!==-1 && style.svg !== value) { 383 if ((style.svgAttr === "stroke" || style.svgAttr === "fill") && value.indexOf("rgba") !== -1) { 384 //separate alpha value, since illustrator can't handle it 385 regex = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?\.?\d*)\s*\)/gi; 386 matches = regex.exec(value); 387 currentElement.setAttribute(style.svgAttr, format("rgb({r},{g},{b})", {r:matches[1], g:matches[2], b:matches[3]})); 388 //should take globalAlpha here 389 var opacity = matches[4]; 390 var globalAlpha = this.globalAlpha; 391 if (globalAlpha != null) { 392 opacity *= globalAlpha; 393 } 394 currentElement.setAttribute(style.svgAttr+"-opacity", opacity); 395 } else { 396 var attr = style.svgAttr; 397 if (keys[i] === 'globalAlpha') { 398 attr = type+'-'+style.svgAttr; 399 if (currentElement.getAttribute(attr)) { 400 //fill-opacity or stroke-opacity has already been set by stroke or fill. 401 continue; 402 } 403 } 404 //otherwise only update attribute if right type, and n
404ot svg default 405 currentElement.setAttribute(attr, value); 406 } 407 } 408 } 409 } 410 }; 411 412 /** 413 * Will return the closest group or svg node. May return the current element. 414 * @private 415 */ 416 ctx.prototype.__closestGroupOrSvg = function (node) { 417 node = node || this.__currentElement; 418 if (node.nodeName === "g" || node.nodeName === "svg") { 419 return node; 420 } else { 421 return this.__closestGroupOrSvg(node.parentNode); 422 } 423 }; 424 425 /** 426 * Returns the serialized value of the svg so far 427 * @param fixNamedEntities - Standalone SVG doesn't support named entities, which document.createTextNode encodes. 428 * If true, we attempt to find all named entities and encode it as a numeric entity. 429 * @return serialized svg 430 */ 431 ctx.prototype.getSerializedSvg = function (fixNamedEntities) { 432 var serialized = new XMLSerializer().serializeToString(this.__root), 433 keys, i, key, value, regexp, xmlns; 434 435 //IE search for a duplicate xmnls because they didn't implement setAttributeNS correctly 436 xmlns = /xmlns="http:\/\/www\.w3\.org\/2000\/svg".+xmlns="http:\/\/www\.w3\.org\/2000\/svg/gi; 437 if (xmlns.test(serialized)) { 438 serialized = serialized.replace('xmlns="http://www.w3.org/2000/svg','xmlns:xlink="http://www.w3.org/1999/xlink'); 439 } 440 441 if (fixNamedEntities) { 442 keys = Object.keys(namedEntities); 443 //loop over each named entity and replace with the proper equivalent. 444 for (i=0; i<keys.length; i++) { 445 key = keys[i]; 446 value = namedEntities[key]; 447 regexp = new RegExp(key, "gi"); 448 if (regexp.test(serialized)) { 449 serialized = serialized.replace(regexp, value); 450 } 451 } 452 } 453 454 return serialized; 455 }; 456 457 458 /** 459 * Returns the root svg 460 * @return 461 */ 462 ctx.prototype.getSvg = function () { 463 return this.__root; 464 }; 465 /** 466 * Will generate a group tag. 467 */ 468 ctx.prototype.save = function () { 469 var group = this.__createElement("g"); 470 var parent = this.__closestGroupOrSvg(); 471 this.__groupStack.push(parent); 472 parent.appendChild(group); 473 this.__currentElement = group; 474 this.__stack.push(this.__getStyleState()); 475 }; 476 /** 477 * Sets current element to parent, or just root if already root 478 */ 479 ctx.prototype.restore = function () { 480 this.__currentElement = this.__groupStack.pop(); 481 this.__currentElementsToStyle = null; 482 //Clearing canvas will make the poped group invalid, currentElement is set to the root group node. 483 if (!this.__currentElement) { 484 this.__currentElement = this.__root.childNodes[1]; 485 } 486 var state = this.__stack.pop(); 487 this.__applyStyleState(state); 488 }; 489 490 /** 491 * Helper method to add transform 492 * @private 493 */ 494 ctx.prototype.__addTransform = function (t) { 495 //if the current element has siblings, add another group 496 var parent = this.__closestGroupOrSvg(); 497 if (parent.childNodes.length > 0) { 498 if (this.__currentElement.nodeName === "path") { 499 if (!this.__currentElementsToStyle) this.__currentElementsToStyle = {element: parent, children: []}; 500 this.__currentElementsToStyle.children.push(this.__currentElement) 501 this.__applyCurrentDefaultPath(); 502 } 503 504 var group = this.__createElement("g"); 505 parent.appendChild(group); 506 this.__currentElement = group; 507 } 508 509 var transform = this.__currentElement.getAttribute("transform"); 510 if (transform) { 511 transform += " "; 512 } else { 513 transform = ""; 514 } 515 transform += t; 516 this.__currentElement.setAttribute("transform", transform); 517 }; 518 519 /** 520 * scales the current element 521 */ 522 ctx.prototype.scale = function (x, y) { 523 if (y === undefined) { 524 y = x; 525 } 526 this.__addTransform(format("scale({x},{y})", {x:x, y:y})); 527 }; 528 529 /** 530 * rotates the current element 531 */ 532 ctx.prototype.rotate = function (angle) { 533 var degrees = (angle * 180 / Math.PI); 534 this.__addTransform(format("rotate({angle},{cx},{cy})", {angle:degrees, cx:0, cy:0})); 535 }; 536 537 /** 538 * translates the current element 539 */ 540 ctx.prototype.translate = function (x, y) { 541 this.__addTransform(format("translate({x},{y})", {x:x,y:y})); 542 }; 543 544 /** 545 * applies a transform to the current element 546 */ 547 ctx.prototype.transform = function (a, b, c, d, e, f) { 548 this.__addTransform(format("matrix({a},{b},{c},{d},{e},{f})", {a:a, b:b, c:c, d:d, e:e, f:f})); 549 }; 550 551 /** 552 * Create a new Path Element 553 */ 554 ctx.prototype.beginPath = function () { 555 var path, parent; 556 557 // Note that there is only one current default path, it is not part of the drawing state. 558 // See also: https://html.spec.whatwg.org/multipage/scripting.html#current-default-path 559 this.__currentDefaultPath = ""; 560 this.__currentPosition = {}; 561 562 path = this.__createElement("path", {}, true); 563 parent = this.__closestGroupOrSvg(); 564 parent.appendChild(path); 565 this.__currentElement = path; 566 }; 567 568 /** 569 * Helper function to apply currentDefaultPath to current path element 570 * @private 571 */ 572 ctx.prototype.__applyCurrentDefaultPath = function () { 573 var currentElement = this.__currentElement; 574 if (currentElement.nodeName === "path") { 575 currentElement.setAttribute("d", this.__currentDefaultPath); 576 } else {
577 console.error("Attempted to apply path command to node", currentElement.nodeName); 578 } 579 }; 580 581 /** 582 * Helper function to add path command 583 * @private 584 */ 585 ctx.prototype.__addPathCommand = function (command) { 586 this.__currentDefaultPath += " "; 587 this.__currentDefaultPath += command; 588 }; 589 590 /** 591 * Adds the move command to the current path element, 592 * if the currentPathElement is not empty create a new path element 593 */ 594 ctx.prototype.moveTo = function (x,y) { 595 if (this.__currentElement.nodeName !== "path") { 596 this.beginPath(); 597 } 598 599 // creates a new subpath with the given point 600 this.__currentPosition = {x: x, y: y}; 601 this.__addPathCommand(format("M {x} {y}", {x:x, y:y})); 602 }; 603 604 /** 605 * Closes the current path 606 */ 607 ctx.prototype.closePath = function () { 608 if (this.__currentDefaultPath) { 609 this.__addPathCommand("Z"); 610 } 611 }; 612 613 /** 614 * Adds a line to command 615 */ 616 ctx.prototype.lineTo = function (x, y) { 617 this.__currentPosition = {x: x, y: y}; 618 if (this.__currentDefaultPath.indexOf('M') > -1) { 619 this.__addPathCommand(format("L {x} {y}", {x:x, y:y})); 620 } else { 621 this.__addPathCommand(format("M {x} {y}", {x:x, y:y})); 622 } 623 }; 624 625 /** 626 * Add a bezier command 627 */ 628 ctx.prototype.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) { 629 this.__currentPosition = {x: x, y: y}; 630 this.__addPathCommand(format("C {cp1x} {cp1y} {cp2x} {cp2y} {x} {y}", 631 {cp1x:cp1x, cp1y:cp1y, cp2x:cp2x, cp2y:cp2y, x:x, y:y})); 632 }; 633 634 /** 635 * Adds a quadratic curve to command 636 */ 637 ctx.prototype.quadraticCurveTo = function (cpx, cpy, x, y) { 638 this.__currentPosition = {x: x, y: y}; 639 this.__addPathCommand(format("Q {cpx} {cpy} {x} {y}", {cpx:cpx, cpy:cpy, x:x, y:y})); 640 }; 641 642 643 /** 644 * Return a new normalized vector of given vector 645 */ 646 var normalize = function (vector) { 647 var len = Math.sqrt(vector[0] * vector[0] + vector[1] * vector[1]); 648 return [vector[0] / len, vector[1] / len]; 649 }; 650 651 /** 652 * Adds the arcTo to the current path 653 * 654 * @see http://www.w3.org/TR/2015/WD-2dcontext-20150514/#dom-context-2d-arcto 655 */ 656 ctx.prototype.arcTo = function (x1, y1, x2, y2, radius) { 657 // Let the point (x0, y0) be the last point in the subpath. 658 var x0 = this.__currentPosition && this.__currentPosition.x; 659 var y0 = this.__currentPosition && this.__currentPosition.y; 660 661 // First ensure there is a subpath for (x1, y1). 662 if (typeof x0 == "undefined" || typeof y0 == "undefined") { 663 return; 664 } 665 666 // Negative values for radius must cause the implementation to throw an IndexSizeError exception. 667 if (radius < 0) { 668 throw new Error("IndexSizeError: The radius provided (" + radius + ") is negative."); 669 } 670 671 // If the point (x0, y0) is equal to the point (x1, y1), 672 // or if the point (x1, y1) is equal to the point (x2, y2), 673 // or if the radius radius is zero, 674 // then the method must add the point (x1, y1) to the subpath, 675 // and connect that point to the previous point (x0, y0) by a straight line. 676 if (((x0 === x1) && (y0 === y1)) 677 || ((x1 === x2) && (y1 === y2)) 678 || (radius === 0)) { 679 this.lineTo(x1, y1); 680 return; 681 } 682 683 // Otherwise, if the points (x0, y0), (x1, y1), and (x2, y2) all lie on a single straight line, 684 // then the method must add the point (x1, y1) to the subpath, 685 // and connect that point to the previous point (x0, y0) by a straight line. 686 var unit_vec_p1_p0 = normalize([x0 - x1, y0 - y1]); 687 var unit_vec_p1_p2 = normalize([x2 - x1, y2 - y1]); 688 if (unit_vec_p1_p0[0] * unit_vec_p1_p2[1] === unit_vec_p1_p0[1] * unit_vec_p1_p2[0]) { 689 this.lineTo(x1, y1); 690 return; 691 } 692 693 // Otherwise, let The Arc be the shortest arc given by circumference of the circle that has radius radiu
vendor: 15,864 bytes, lines 693-1142
693s, 694 // and that has one point tangent to the half-infinite line that crosses the point (x0, y0) and ends at the point (x1, y1), 695 // and that has a different point tangent to the half-infinite line that ends at the point (x1, y1), and crosses the point (x2, y2). 696 // The points at which this circle touches these two lines are called the start and end tangent points respectively. 697 698 // note that both vectors are unit vectors, so the length is 1 699 var cos = (unit_vec_p1_p0[0] * unit_vec_p1_p2[0] + unit_vec_p1_p0[1] * unit_vec_p1_p2[1]); 700 var theta = Math.acos(Math.abs(cos)); 701 702 // Calculate origin 703 var unit_vec_p1_origin = normalize([ 704 unit_vec_p1_p0[0] + unit_vec_p1_p2[0], 705 unit_vec_p1_p0[1] + unit_vec_p1_p2[1] 706 ]); 707 var len_p1_origin = radius / Math.sin(theta / 2); 708 var x = x1 + len_p1_origin * unit_vec_p1_origin[0]; 709 var y = y1 + len_p1_origin * unit_vec_p1_origin[1]; 710 711 // Calculate start angle and end angle 712 // rotate 90deg clockwise (note that y axis points to its down) 713 var unit_vec_origin_start_tangent = [ 714 -unit_vec_p1_p0[1], 715 unit_vec_p1_p0[0] 716 ]; 717 // rotate 90deg counter clockwise (note that y axis points to its down) 718 var unit_vec_origin_end_tangent = [ 719 unit_vec_p1_p2[1], 720 -unit_vec_p1_p2[0] 721 ]; 722 var getAngle = function (vector) { 723 // get angle (clockwise) between vector and (1, 0) 724 var x = vector[0]; 725 var y = vector[1]; 726 if (y >= 0) { // note that y axis points to its down 727 return Math.acos(x); 728 } else { 729 return -Math.acos(x); 730 } 731 }; 732 var startAngle = getAngle(unit_vec_origin_start_tangent); 733 var endAngle = getAngle(unit_vec_origin_end_tangent); 734 735 // Connect the point (x0, y0) to the start tangent point by a straight line 736 this.lineTo(x + unit_vec_origin_start_tangent[0] * radius, 737 y + unit_vec_origin_start_tangent[1] * radius); 738 739 // Connect the start tangent point to the end tangent point by arc 740 // and adding the end tangent point to the subpath. 741 this.arc(x, y, radius, startAngle, endAngle); 742 }; 743 744 /** 745 * Sets the stroke property on the current element 746 */ 747 ctx.prototype.stroke = function () { 748 if (this.__currentElement.nodeName === "path") { 749 this.__currentElement.setAttribute("paint-order", "fill stroke markers"); 750 } 751 this.__applyCurrentDefaultPath(); 752 this.__applyStyleToCurrentElement("stroke"); 753 }; 754 755 /** 756 * Sets fill properties on the current element 757 */ 758 ctx.prototype.fill = function () { 759 if (this.__currentElement.nodeName === "path") { 760 this.__currentElement.setAttribute("paint-order", "stroke fill markers"); 761 } 762 this.__applyCurrentDefaultPath(); 763 this.__applyStyleToCurrentElement("fill"); 764 }; 765 766 /** 767 * Adds a rectangle to the path. 768 */ 769 ctx.prototype.rect = function (x, y, width, height) { 770 if (this.__currentElement.nodeName !== "path") { 771 this.beginPath(); 772 } 773 this.moveTo(x, y); 774 this.lineTo(x+width, y); 775 this.lineTo(x+width, y+height); 776 this.lineTo(x, y+height); 777 this.lineTo(x, y); 778 this.closePath(); 779 }; 780 781 782 /** 783 * adds a rectangle element 784 */ 785 ctx.prototype.fillRect = function (x, y, width, height) { 786 var rect, parent; 787 rect = this.__createElement("rect", { 788 x : x, 789 y : y, 790 width : width, 791 height : height 792 }, true); 793 parent = this.__closestGroupOrSvg(); 794 parent.appendChild(rect); 795 this.__currentElement = rect; 796 this.__applyStyleToCurrentElement("fill"); 797 }; 798 799 /** 800 * Draws a rectangle with no fill 801 * @param x 802 * @param y 803 * @param width 804 * @param height 805 */ 806 ctx.prototype.strokeRect = function (x, y, width, height) { 807 var rect, parent; 808 rect = this.__createElement("rect", { 809 x : x, 810 y : y, 811 width : width, 812 height : height 813 }, true); 814 parent = this.__closestGroupOrSvg(); 815 parent.appendChild(rect); 816 this.__currentElement = rect; 817 this.__applyStyleToCurrentElement("stroke"); 818 }; 819 820 821 /** 822 * Clear entire canvas: 823 * 1. save current transforms 824 * 2. remove all the childNodes of the root g element 825 */ 826 ctx.prototype.__clearCanvas = function () { 827 var current = this.__closestGroupOrSvg(), 828 transform = current.getAttribute("transform"); 829 var rootGroup = this.__root.childNodes[1]; 830 var childNodes = rootGroup.childNodes; 831 for (var i = childNodes.length - 1; i >= 0; i--) { 832 if (childNodes[i]) { 833 rootGroup.removeChild(childNodes[i]); 834 } 835 } 836 this.__currentElement = rootGroup; 837 //reset __groupStack as all the child group nodes are all removed. 838 this.__groupStack = []; 839 if (transform) { 840 this.__addTransform(transform); 841 } 842 }; 843 844 /** 845 * "Clears" a canvas by just drawing a white rectangle in the current group. 846 */ 847 ctx.prototype.clearRect = function (x, y, width, height) { 848 //clear entire canvas 849 if (x === 0 && y === 0 && width === this.width && height === this.height) { 850 this.__clearCanvas(); 851 return; 852 } 853 var rect, parent = this.__closestGroupOrSvg(); 854 rect = this.__createElement("rect", { 855 x : x, 856 y : y, 857 width : width, 858 height : height, 859 fill : "#FFFFFF" 860 }, true); 861 parent.appendChild(rect); 862 }; 863 864 /** 865 * Adds a linear gradient to a defs tag. 866 * Returns a canvas gradient object that has a reference to it's parent def 867 */ 868 ctx.prototype.createLinearGradient = function (x1, y1, x2, y2) { 869 var grad = this.__createElement("linearGradient", { 870 id : randomString(this.__ids), 871 x1 : x1+"px", 872 x2 : x2+"px", 873 y1 : y1+"px", 874 y2 : y2+"px", 875 "gradientUnits" : "userSpaceOnUse" 876 }, false); 877 this.__defs.appendChild(grad); 878 return new CanvasGradient(grad, this); 879 }; 880 881 /** 882 * Adds a radial gradient to a defs tag. 883 * Returns a canvas gradient object that has a reference to it's parent def 884 */ 885 ctx.prototype.createRadialGradient = function (x0, y0, r0, x1, y1, r1) { 886 var grad = this.__createElement("radialGradient", { 887 id : randomString(this.__ids), 888 cx : x1+"px", 889 cy : y1+"px", 890 r : r1+"px", 891 fx : x0+"px", 892 fy : y0+"px", 893 "gradientUnits" : "userSpaceOnUse" 894 }, false); 895 this.__defs.appendChild(grad); 896 return new CanvasGradient(grad, this); 897 898 }; 899 900 /** 901 * Parses the font string and returns svg mapping 902 * @private 903 */ 904 ctx.prototype.__parseFont = function () { 905 var regex = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\'\"\sa-z0-9]+?)\s*$/i; 906 var fontPart = regex.exec( this.font ); 907 var data = { 908 style : fontPart[1] || 'normal', 909 size : fontPart[4] || '10px', 910 family : fontPart[6] || 'sans-serif', 911 weight: fontPart[3] || 'normal', 912 decoration : fontPart[2] || 'normal', 913 href : null 914 }; 915 916 //canvas doesn't support underline natively, but we can pass this attribute 917 if (this.__fontUnderline === "underline") { 918 data.decoration = "underline"; 919 } 920 921 //canvas also doesn't support linking, but we can pass this as well 922 if (this.__fontHref) { 923 data.href = this.__fontHref; 924 } 925 926 return data; 927 }; 928 929 /** 930 * Helper to link text fragments 931 * @param font 932 * @param element 933 * @return {*} 934 * @private 935 */ 936 ctx.prototype.__wrapTextLink = function (font, element) { 937 if (font.href) { 938 var a = this.__createElement("a"); 939 a.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", font.href); 940 a.appendChild(element); 941 return a; 942 } 943 return element; 944 }; 945 946 /** 947 * Fills or strokes text 948 * @param text 949 * @param x 950 * @param y 951 * @param action - stroke or fill 952 * @private 953 */ 954 ctx.prototype.__applyText = function (text, x, y, action) { 955 var font = this.__parseFont(), 956 parent = this.__closestGroupOrSvg(), 957 textElement = this.__createElement("text", { 958 "font-family" : font.family, 959 "font-size" : font.size, 960 "font-style" : font.style, 961 "font-weight" : font.weight, 962 "text-decoration" : font.decoration, 963 "x" : x, 964 "y" : y, 965 "text-anchor": getTextAnchor(this.textAlign), 966 "dominant-baseline": getDominantBaseline(this.textBaseline) 967 }, true); 968 969 textElement.appendChild(this.__document.createTextNode(text)); 970 this.__currentElement = textElement; 971 this.__applyStyleToCurrentElement(action); 972 parent.appendChild(this.__wrapTextLink(font,textElement)); 973 }; 974 975 /** 976 * Creates a text element 977 * @param text 978 * @param x 979 * @param y 980 */ 981 ctx.prototype.fillText = function (text, x, y) { 982 this.__applyText(text, x, y, "fill"); 983 }; 984 985 /** 986 * Strokes text 987 * @param text 988 * @param x 989 * @param y 990 */ 991 ctx.prototype.strokeText = function (text, x, y) { 992 this.__applyText(text, x, y, "stroke"); 993 }; 994 995 /** 996 * No need to implement this for svg. 997 * @param text 998 * @return {TextMetrics} 999 */ 1000 ctx.prototype.measureText = function (text) { 1001 this.__ctx.font = this.font; 1002 return this.__ctx.measureText(text); 1003 }; 1004 1005 /** 1006 * Arc command! 1007 */ 1008 ctx.prototype.arc = function (x, y, radius, startAngle, endAngle, counterClockwise) { 1009 // in canvas no circle is drawn if no angle is provided. 1010 if (startAngle === endAngle) { 1011 return; 1012 } 1013 startAngle = startAngle % (2*Math.PI); 1014 endAngle = endAngle % (2*Math.PI); 1015 if (startAngle === endAngle) { 1016 //circle time! subtract some of the angle so svg is happy (svg elliptical arc can't draw a full circle) 1017 endAngle = ((endAngle + (2*Math.PI)) - 0.001 * (counterClockwise ? -1 : 1)) % (2*Math.PI); 1018 } 1019 var endX = x+radius*Math.cos(endAngle), 1020 endY = y+radius*Math.sin(endAngle), 1021 startX = x+radius*Math.cos(startAngle), 1022 startY = y+radius*Math.sin(startAngle), 1023 sweepFlag = counterClockwise ? 0 : 1, 1024 largeArcFlag = 0, 1025 diff = endAngle - startAngle; 1026 1027 // https://github.com/gliffy/canvas2svg/issues/4 1028 if (diff < 0) { 1029 diff += 2*Math.PI; 1030 } 1031 1032 if (counterClockwise) { 1033 largeArcFlag = diff > Math.PI ? 0 : 1; 1034 } else { 1035 largeArcFlag = diff > Math.PI ? 1 : 0; 1036 } 1037 1038 this.lineTo(startX, startY); 1039 this.__addPathCommand(format("A {rx} {ry} {xAxisRotation} {largeArcFlag} {sweepFlag} {endX} {endY}", 1040 {rx:radius, ry:radius, xAxisRotation:0, largeArcFlag:largeArcFlag, sweepFlag:sweepFlag, endX:endX, endY:endY})); 1041 1042 this.__currentPosition = {x: endX, y: endY}; 1043 }; 1044 1045 /** 1046 * Generates a ClipPath from the clip command. 1047 */ 1048 ctx.prototype.clip = function () { 1049 var group = this.__closestGroupOrSvg(), 1050 clipPath = this.__createElement("clipPath"), 1051 id = randomString(this.__ids), 1052 newGroup = this.__createElement("g"); 1053 1054 this.__applyCurrentDefaultPath(); 1055 group.removeChild(this.__currentElement); 1056 clipPath.setAttribute("id", id); 1057 clipPath.appendChild(this.__currentElement); 1058 1059 this.__defs.appendChild(clipPath); 1060 1061 //set the clip path to this group 1062 group.setAttribute("clip-path", format("url(#{id})", {id:id})); 1063 1064 //clip paths can be scaled and transformed, we need to add another wrapper group to avoid later transformations 1065 // to this path 1066 group.appendChild(newGroup); 1067 1068 this.__currentElement = newGroup; 1069 1070 }; 1071 1072 /** 1073 * Draws a canvas, image or mock context to this canvas. 1074 * Note that all svg dom manipulation uses node.childNodes rather than node.children for IE support. 1075 * http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-drawimage 1076 */ 1077 ctx.prototype.drawImage = function () { 1078 //convert arguments to a real array 1079 var args = Array.prototype.slice.call(arguments), 1080 image=args[0], 1081 dx, dy, dw, dh, sx=0, sy=0, sw, sh, parent, svg, defs, group, 1082 currentElement, svgImage, canvas, context, id; 1083 1084 if (args.length === 3) { 1085 dx = args[1]; 1086 dy = args[2]; 1087 sw = image.width; 1088 sh = image.height; 1089 dw = sw; 1090 dh = sh; 1091 } else if (args.length === 5) { 1092 dx = args[1]; 1093 dy = args[2]; 1094 dw = args[3]; 1095 dh = args[4]; 1096 sw = image.width; 1097 sh = image.height; 1098 } else if (args.length === 9) { 1099 sx = args[1]; 1100 sy = args[2]; 1101 sw = args[3]; 1102 sh = args[4]; 1103 dx = args[5]; 1104 dy = args[6]; 1105 dw = args[7]; 1106 dh = args[8]; 1107 } else { 1108 throw new Error("Inavlid number of arguments passed to drawImage: " + arguments.length); 1109 } 1110 1111 parent = this.__closestGroupOrSvg(); 1112 currentElement = this.__currentElement; 1113 var translateDirective = "translate(" + dx + ", " + dy + ")"; 1114 if (image instanceof ctx) { 1115 //canvas2svg mock canvas context. In the future we may want to clone nodes instead. 1116 //also I'm currently ignoring dw, dh, sw, sh, sx, sy for a mock context. 1117 svg = image.getSvg().cloneNode(true); 1118 if (svg.childNodes && svg.childNodes.length > 1) { 1119 defs = svg.childNodes[0]; 1120 while(defs.childNodes.length) { 1121 id = defs.childNodes[0].getAttribute("id"); 1122 this.__ids[id] = id; 1123 this.__defs.appendChild(defs.childNodes[0]); 1124 } 1125 group = svg.childNodes[1]; 1126 if (group) { 1127 //save original transform 1128 var originTransform = group.getAttribute("transform"); 1129 var transformDirective; 1130 if (originTransform) { 1131 transformDirective = originTransform+" "+translateDirective; 1132 } else { 1133 transformDirective = translateDirective; 1134 } 1135 group.setAttribute("transform", transformDirective); 1136 parent.appendChild(group); 1137 } 1138 } 1139 } else if (image.nodeName === "CANVAS" || image.nodeName === "IMG") { 1140 //canvas or image 1141 svgImage = this.__createElement("image"); 1142 svgImage.setAttribute("width", dw);
1143 svgImage.setAttribute("height", dh); 1144 svgImage.setAttribute("preserveAspectRatio", "none"); 1145 1146 if (sx || sy || sw !== image.width || sh !== image.height) { 1147 //crop the image using a temporary canvas 1148 canvas = this.__document.createElement("canvas"); 1149 canvas.width = dw; 1150 canvas.height = dh; 1151 context = canvas.getContext("2d"); 1152 context.drawImage(image, sx, sy, sw, sh, 0, 0, dw, dh); 1153 image = canvas; 1154 } 1155 svgImage.setAttribute("transform", translateDirective); 1156 svgImage.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", 1157 image.nodeName === "CANVAS" ? image.toDataURL() : image.getAttribute("src")); 1158 parent.appendChild(svgImage); 1159 } 1160 }; 1161 1162 /** 1163 * Generates a pattern tag 1164 */ 1165 ctx.prototype.createPattern = function (image, repetition) { 1166 var pattern = this.__document.createElementNS("http://www.w3.org/2000/svg", "pattern"), id = randomString(this.__ids), 1167 img; 1168 pattern.setAttribute("id", id); 1169 pattern.setAttribute("width", image.width); 1170 pattern.setAttribute("height", image.height); 1171 if (image.nodeName === "CANVAS" || image.nodeName === "IMG") { 1172 img = this.__document.createElementNS("http://www.w3.org/2000/svg", "image"); 1173 img.setAttribute("width", image.width); 1174 img.setAttribute("height", image.height); 1175 img.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", 1176 image.nodeName === "CANVAS" ? image.toDataURL() : image.getAttribute("src")); 1177 pattern.appendChild(img); 1178 this.__defs.appendChild(pattern); 1179 } else if (image instanceof ctx) { 1180 pattern.appendChild(image.__root.childNodes[1]); 1181 this.__defs.appendChild(pattern); 1182 } 1183 return new CanvasPattern(pattern, this); 1184 }; 1185 1186 ctx.prototype.setLineDash = function (dashArray) { 1187 if (dashArray && dashArray.length > 0) { 1188 this.lineDash = dashArray.join(","); 1189 } else { 1190 this.lineDash = null; 1191 } 1192 }; 1193 1194 /** 1195 * Not yet implemented 1196 */ 1197 ctx.prototype.drawFocusRing = function () {}; 1198 ctx.prototype.createImageData = function () {}; 1199 ctx.prototype.getImageData = function () {}; 1200 ctx.prototype.putImageData = function () {}; 1201 ctx.prototype.globalCompositeOperation = function () {}; 1202 ctx.prototype.setTransform = function () {}; 1203 1204 ctx.prototype.getContext = function (contextId) { 1205 if (contextId=="2d" || contextId=="2D") { 1206 return this; 1207 } 1208 return null; 1209 } 1210 1211 ctx.prototype.style = function () { 1212 return this.__canvas.style 1213 } 1214 1215 ctx.prototype.getAttribute = function (name) { 1216 return this[name]; 1217 } 1218 1219 ctx.prototype.addEventListener = function(type, listener, eventListenerOptions) { 1220 console.log("canvas2svg.addEventListener() not implemented.") 1221 } 1222 1223 //add options for alternative namespace 1224 if (typeof window === "object") { 1225 window.C2S = ctx; 1226 } 1227 1228 // CommonJS/Browserify 1229 if (typeof module === "object" && typeof module.exports === "object") { 1230 module.exports = ctx; 1231 } 1232 1233}());
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.