diff --git a/canvas2svg.js b/canvas2svg.js index e34309a..cb09113 100644 --- a/canvas2svg.js +++ b/canvas2svg.js @@ -144,7 +144,7 @@ svgAttr : "opacity", canvas : 1, svg : 1, - apply : "fill stroke" + apply : "fill stroke" }, "font":{ //font converts to multiple svg attributes, there is custom logic for this @@ -368,10 +368,26 @@ regex = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?\.?\d*)\s*\)/gi; matches = regex.exec(value); this.__currentElement.setAttribute(style.svgAttr, format("rgb({r},{g},{b})", {r:matches[1], g:matches[2], b:matches[3]})); - this.__currentElement.setAttribute(style.svgAttr+"-opacity", matches[4]); + //should take globalAlpha here + var opacity = matches[4]; + var globalAlpha = this.globalAlpha; + if (globalAlpha != null) { + opacity *= globalAlpha; + } + this.__currentElement.setAttribute(style.svgAttr+"-opacity", opacity); } else { + var attr = style.svgAttr; + if (keys[i] === 'globalAlpha') { + attr = type+'-'+style.svgAttr; + if (this.__currentElement.getAttribute(attr)) { + //fill-opacity or stroke-opacity has already been set by stroke or fill. + continue; + } + } //otherwise only update attribute if right type, and not svg default - this.__currentElement.setAttribute(style.svgAttr, value); + this.__currentElement.setAttribute(attr, value); + + } } } diff --git a/test/unit.spec.js b/test/unit.spec.js index e8f05a7..bcafbd1 100644 --- a/test/unit.spec.js +++ b/test/unit.spec.js @@ -296,4 +296,40 @@ describe('canvas2svg', function() { }); }); -}); \ No newline at end of file + + describe("supports globalOpacity", function() { + it("set stroke-opacity when stroking and set fill-opacity when filling",function() { + var ctx = new C2S(); + ctx.globalAlpha = 0.5; + ctx.moveTo(5,5); + ctx.lineTo(15,15); + ctx.stroke(); + var svg = ctx.getSvg(); + expect(svg.querySelector("path").getAttribute("stroke-opacity")).to.equal('0.5'); + ctx.globalAlpha = 0.1; + ctx.fillStyle = "#000000"; + ctx.fill(); + expect(svg.querySelector("path").getAttribute("fill-opacity")).to.equal('0.1'); + //stroke-opacity stays o.5 + expect(svg.querySelector("path").getAttribute("stroke-opacity")).to.equal('0.5'); + }); + + it("added into color opacity when stroking or filling with rgba style color. ",function() { + var ctx = new C2S(); + ctx.strokeStyle="rgba(0,0,0,0.8)"; + ctx.globalAlpha = 0.5; + ctx.moveTo(5,5); + ctx.lineTo(15,15); + ctx.stroke(); + var svg = ctx.getSvg(); + expect(svg.querySelector("path").getAttribute("stroke")).to.equal('rgb(0,0,0)'); + //stroke-opacity should be globalAlpha*(alpha in rgba) + expect(svg.querySelector("path").getAttribute("stroke-opacity")).to.equal(''+0.8*0.5); + ctx.globalAlpha = 0.6; + ctx.fillStyle = "rgba(0,0,0,0.6)"; + ctx.fill(); + expect(svg.querySelector("path").getAttribute("fill-opacity")).to.equal(''+0.6*0.6); + expect(svg.querySelector("path").getAttribute("stroke-opacity")).to.equal(''+0.8*0.5); + }); + }); +});