Giter VIP home page Giter VIP logo

svgcanvas's Introduction

SVGCanvas

Draw on SVG using Canvas's 2D Context API. A maintained fork of gliffy's canvas2svg.

Demo

https://zenozeng.github.io/svgcanvas/test/

How it works

We create a mock 2d canvas context. Use the canvas context like you would on a normal canvas. As you call methods, we build up a scene graph in SVG.

Usage

import { Context } from "svgcanvas";

const ctx = new Context(500, 500);

// draw your canvas like you would normally
ctx.fillStyle = "red";
ctx.fillRect(100, 100, 100, 100);

// serialize your SVG
const mySerializedSVG = ctx.getSerializedSvg();

Wrapping canvas elements:

import { Context, Element } from "svgcanvas";

const canvas = document.createElement("canvas");
const context2D = canvas.getContext("2d");

// more options to pass into constructor:
const options = {
  height: 2000, // falsy values get converted to 500
  width: 0 / 0, // falsy values get converted to 500
  ctx: context2D, // existing Context2D to wrap around
  enableMirroring: false, // whether canvas mirroring (get image data) is enabled (defaults to false)
  document: undefined, // overrides default document object
};

// Creates a mock canvas context (mocks `context2D` above)
const ctx = new Context(options);

// draw your canvas like you would normally
ctx.fillStyle = "red";
ctx.fillRect(100, 100, 100, 100);

ctx.getSerializedSvg(); // returns the serialized SVG
ctx.getSvg(); // returns the inline svg element

// Creates a mock canvas element (mocks `canvas` above)
const dom = new Element(options);
dom.ctx; // the internal context, via `new Context(options)`
dom.wrapper; // a div with the svg as a child
dom.svg; // the inline svg element

Tests

https://zenozeng.github.io/p5.js-svg/test/

License

This library is licensed under the MIT license.

svgcanvas's People

Contributors

zenozeng avatar gwwar avatar fuzhenn avatar conradirwin avatar mudcube avatar k1w1 avatar kokutoru avatar watcherdm avatar validark avatar janpot avatar stafyniaksacha avatar spanktar avatar lemonpi avatar mauriciodarocha avatar msftenhanceprovenance avatar x4d3 avatar

Stargazers

Vinh Quốc Nguyễn avatar Nassredean Nasseri avatar Patrick Khoo avatar Phillip Novess avatar Giulian Drimba avatar barkpixels avatar Rhea Myers avatar  avatar  avatar  avatar  avatar  avatar Jiayi Hu avatar  avatar Max Nest avatar  avatar adampweb avatar WeiKuang avatar Technici4n avatar Noam Teyssier avatar  avatar eulyoung avatar Minkyu Lee avatar lrtvri avatar Ta Tien Dat (Cody) avatar Kyle Harrity avatar Huub avatar  avatar Liu Yue avatar Joey Janson avatar Ali Thanikkal avatar Rustam Giliaziev avatar Josh avatar Moritz Klack avatar  avatar  avatar  avatar Colin Diesh avatar Sen Zhang avatar Soumyajit Pathak avatar Second Datke avatar Emmanuel Salomon avatar Arthur Corenzan avatar Luiz Bills avatar  avatar Andrey Sidorov avatar Tenvi avatar Ian Storm Taylor avatar Davo Galavotti avatar Jason Grant avatar Poren Chiang avatar Tom Hermans avatar Andrew Wright avatar  avatar Daniel T. avatar  avatar Jonathan Canupp avatar Michal Kijowski avatar Lucas Martín avatar Boris Dudelsack avatar Michael Schwartz avatar Carlos Martínez avatar

Watchers

Carlos Martínez avatar Michael Borcherds avatar James Cloos avatar  avatar Colin Diesh avatar  avatar

svgcanvas's Issues

C2S doesn't work with new version of Chart.js : Attempted to apply path command to node g

I got several issue trying to use C2S to export a graph generated with Chart.js

On stackoverflow, I found out that C2S was lacking some method (getContext, style, getAttribute, and addEventListener) (cf below).

However, new versions of Chart.js still seems to be doing something that C2S doesn't like.

Initially I used a npm package that seems to work (but without any git associated) at the exception of setTransform and resetTransform that weren't implemented ( https://www.npmjs.com/package/canvas-to-svg ). This npm package seems to be maintained by @rob-gordon (https://github.com/rob-gordon), and I think is from this git https://github.com/tone-row/canvas-to-svg

I then tried several versions of C2S. Yours seems to be one of the most maintained. Only the grid is drawn, and I don't see any error in the console (cf below) : "Attempted to apply path command to node g"

Would you know how I could make it works ?

Missing methods :


ctx.getContext = function (contextId) {
		  if (contextId=="2d" || contextId=="2D") {
		      return this;
		  }
		  return null;
}

ctx.style = function () {
		  return this.__canvas.style
}

ctx.getAttribute = function (name) {
		  return this[name];
}
//ctx.setTransform = function() {}
//ctx.resetTransform = function() {}

ctx.addEventListener =  function(type, listener, eventListenerOptions) {
		  console.log("canvas2svg.addEventListener() not implemented.")
}

Minimal example :

import {Chart, LinearScale, ScatterController, PointElement, LineElement} from 'chart.js';
Chart.register(ScatterController, PointElement, LineElement, LinearScale);

import { Context } from "./svgcanvas-issue-fill-path/";

let config = {
        data: {
        datasets: [{
        	type:'scatter',
        	showLine: true,
            data: [ [3,0], [3,1],[5,5],[7,6],[12,1], [19,2]]
        }],
    },

        options: {
        	animation: false,
            responsive:false,
            maintainAspectRatio: false
        }
    };
    
let ctx = new Context(500,500);

// @ts-ignore
ctx.getContext = function (contextId) {
		  if (contextId=="2d" || contextId=="2D") {
		      return this;
		  }
		  return null;
}

// @ts-ignore
ctx.style = function () {
		  return this.__canvas.style
}

// @ts-ignore
ctx.getAttribute = function (name) {
		  return this[name];
}
//ctx.setTransform = function() {}
//ctx.resetTransform = function() {}

// @ts-ignore
ctx.addEventListener =  function(type, listener, eventListenerOptions) {
		  console.log("canvas2svg.addEventListener() not implemented.")
}

//let canvas = document.getElementById('test');
//new Chart(canvas.getContext('2d'), config);

new Chart(ctx, config);

let str = ctx.getSerializedSvg();

//download(str, 'test.svg', 'image/svg+xml');

Expected :

canvas

Result :
test(52)

Canvas calls that include NaN parameters aren't treated properly

Situation

Sometimes (most often mistakenly), CanvasRenderingContext2D API functions may be called with NaN passed as one or more of the parameters.

Although it is not mentionned in the MDN documentation as far as I could find, it turns out that calls to such functions with NaN as one of the parameters are simply ignored with no errors returned.

As such, the following code here will have three of its lines completely ignored:

let canvas = document.getElementById('test');
let ctx = canvas.getContext('2d');

ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(NaN, 70); // Gets ignored
ctx.lineTo(70, NaN); // Gets ignored
ctx.lineTo(NaN, NaN); // Gets ignored
ctx.lineTo(100, 100);
ctx.stroke();

See for yourself: https://jsfiddle.net/d0bmx5nt/1/

The problem

It however seems that svgcanvas does not acknowledge this, and therefore encodes the NaN values into the exported svg.

Therefore, the following code:

import svgcanvas from 'https://cdn.jsdelivr.net/npm/[email protected]/+esm'

let ctx = new svgcanvas.Context(250, 250);

ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(NaN, 70); // Gets ignored
ctx.lineTo(70, NaN); // Gets ignored
ctx.lineTo(NaN, NaN); // Gets ignored
ctx.lineTo(100, 100);
ctx.stroke();

saveAs(new Blob([ctx.getSerializedSvg()], { type: 'image/svg+xml' }), 'test.svg');

Exports the following SVG file:

<svg version="1.1"
	xmlns="http://www.w3.org/2000/svg"
	xmlns:xlink="http://www.w3.org/1999/xlink" width="500" height="500">
	<defs/>
	<g>
		<path fill="none" stroke="#000000" paint-order="fill stroke markers" d=" M 50 50 L NaN NaN L NaN NaN L NaN NaN L 100 100" stroke-miterlimit="10" stroke-dasharray=""/>
	</g>
</svg>

See for yourself: https://jsfiddle.net/pcrn6471/1/

While some browsers might correctly ignore the commands that involve those NaN values, it is ultimately up to the software you are opening it with to decide what to do with it.

Inkscape, for instance, considers those NaNs as 0s, while Firefox seems to sometimes ignore them, or sometimes invalidate the whole path.

Practical use case

You might think that if there are NaNs in paths, then it's up to the programmer who has put them to fix it.

However, in practice, this very likely won't ever happen.

The reason I met this problem in the first place is when trying to export charts rendered by Chart.JS as SVG files. And even though Chart.JS is a 63.2k stars JS module, there are some draw calls that end up passing NaN to CanvasRenderingContext2D functions. And while yes I suppose an issue could be opened there, why would they bother fixing something that does not trigger any error in the first place nor cause any problem to any Chart.JS user and only affects one module that intercepts function calls that weren't meant to be intercepted in the first place?

Therefore, I think it would be more reasonable to implement a fix for this within svgcanvas, as it would make it more accurate to browsers' behaviour and would avoid opening issues for every module that uses canvas but has such calls happening in the background.

Workaround

In the meantime of this issue being resolved, you can work around the problem with one of these solutions:

  • Override Context.prototype functions to make them return if NaN is passed
  • Proxy Context.prototype functions to make them return if NaN is passed
  • Edit svgcanvas' code to make those functions natively return in case of NaN being passed

Create svg without document

The chess-image-generator package uses node-canvas to create an image of a chess position. Unfortunately I'm a little unhappy with the results, as the chess pieces, which are stored as pngs, become a little blurry on the canvas (see for example here: https://bucket-lichess.vercel.app/api/board?fen=8/6p1/2prppp1/3k4/5PP1/2R5/PP5P/6K1&squares=d8,d6).

Is it possible to use the svgcanvas library to create an svg and convert it to a png image (all on the server)?

I tried to do the following, however it resulted in a document is not defined error which I am not sure how to solve.

const ChessImageGenerator = require('chess-image-generator')
import { createCanvas } from 'canvas'
import { Context } from 'svgcanvas'
const sharp = require('sharp')

// ig <=> ChessImageGenerator object
async function generateBuffer(ig) {
  if (!ig.ready) {
    throw new Error("Load a position first");
  }

  const canvas = createCanvas(ig.size, ig.size)
  const context2D = canvas.getContext('2d')

  // ERROR: document not defined
  const ctx = new Context({
    width: ig.size,
    height: ig.size,
    ctx: context2D,
    document: undefined,
  })
  // create chess pattern and add chess pieces
  for (let i = 0; i < 8; i += 1) {
    for (let j = 0; j < 8; j += 1) {
      const coords = cols[col(j)] + row(i);

      if ((i + j) % 2 === 0) {
        ctx.beginPath();
        ctx.rect(
          ((ig.size / 8) * (7 - j + 1) - ig.size / 8),
          ((ig.size / 8) * i) + ig.padding[0],
          ig.size / 8,
          ig.size / 8
        );
        ctx.fillStyle = ig.dark;
        ctx.fill();
      }
      // ...
      // add chess pieces that are stored as svg files
      // ...
    }
  }

  return sharp(ctx.getSerializedSvg()).png().toBuffer()
}

Implement canvas transformations

Spec: https://html.spec.whatwg.org/multipage/canvas.html#transformations

For zenozeng/p5.js-svg#170

context . scale(x, y)
// Changes the current transformation matrix to apply a scaling transformation with the given characteristics.

context . rotate(angle)
//Changes the current transformation matrix to apply a rotation transformation with the given characteristics. The angle is in radians.

context . translate(x, y)
// Changes the current transformation matrix to apply a translation transformation with the given characteristics.

context . transform(a, b, c, d, e, f)
// Changes the current transformation matrix to apply the matrix given by the arguments as described below.

matrix = context . getTransform()
// Returns a copy of the current transformation matrix, as a newly created DOMMatrix object.

context . setTransform(a, b, c, d, e, f)
// Changes the current transformation matrix to the matrix given by the arguments as described below.

context . setTransform(transform)
// Changes the current transformation matrix to the matrix represented by the passed DOMMatrix2DInit dictionary.

context . resetTransform()
// Changes the current transformation matrix to the identity matrix.

Should merge fixes from pull requests and issues from gliffy

Looks like a lot of folks have found many issues with canvas2svg and some fixes are already available. It would be great if svgcanvas could address these issues. Here is a checklist of issues/pull requests that could be fixed into this project.

Is there an infinite loop in drawImage?

Found this code in the drawImage method in context.js:

svgcanvas/context.js

Lines 1140 to 1144 in 3991b8e

while(defs.childNodes.length) {
id = defs.childNodes[0].getAttribute("id");
this.__ids[id] = id;
this.__defs.appendChild(defs.childNodes[0]);
}

Does defs.childNodes.length ever change? Was this supposed to call defs.childNodes.shift()?

More context:

svgcanvas/context.js

Lines 1134 to 1151 in 3991b8e

if (image instanceof Context) {
//canvas2svg mock canvas context. In the future we may want to clone nodes instead.
//also I'm currently ignoring dw, dh, sw, sh, sx, sy for a mock context.
svg = image.getSvg().cloneNode(true);
if (svg.childNodes && svg.childNodes.length > 1) {
defs = svg.childNodes[0];
while(defs.childNodes.length) {
id = defs.childNodes[0].getAttribute("id");
this.__ids[id] = id;
this.__defs.appendChild(defs.childNodes[0]);
}
group = svg.childNodes[1];
if (group) {
this.__applyTransformation(group, matrix);
parent.appendChild(group);
}
}
} else if (image.nodeName === "CANVAS" || image.nodeName === "IMG") {

Update, this might be the same as:

failed to convert the circle

I tried to convert Canvas to SVG, but failed to convert circles. Circles do not appear in the new SVG.

Here is the API I wrote to implement the transformation:

`import {Context} from 'svgcanvas'
handle_saveSvg() {
let width = this.canvas.canvas.width
let height = this.canvas.canvas.height
console.log(width,height,"rect")
// let C2S = window.C2S
let ctx = new Context(width + 500, height + 500)
console.log(ctx, "ctx")
for (let pen of this.canvas.store.data.pens) {
console.log(pen, "pen")
if (pen.type) {
let line = pen
line.from = {}
line.to = {}
}
this.canvas.renderPenRaw(ctx, pen)
}
console.log(ctx, "ctx1")

  let mySerializedSVG = ctx.getSerializedSvg()
  console.log(mySerializedSVG, "svg")
  mySerializedSVG = mySerializedSVG.replace(
    "<defs/>",
    `<defs>
<style type="text/css"> @font-face { font-family: 'topology'; src: url('https://at.alicdn.com/t/font_1331132_h688rvffmbc.ttf') format('truetype'); } @font-face { font-family: 'ltee'; src: url('https://at.alicdn.com/t/font_2052340_ceohsubmal7.ttf') format('truetype'); } @font-face { font-family: 'ltdx'; src: url('https://at.alicdn.com/t/font_2073009_5ilnjxypv6l.ttf') format('truetype'); } @font-face { font-family: 'ticon'; src: url('https://at.alicdn.com/t/font_1331132_g7tv7fmj6c9.ttf') format('truetype'); } </style>

`
)
mySerializedSVG = mySerializedSVG.replace(/--le5le--/g, '&#x')

  const urlObject = window.URL || window
  const export_blob = new Blob([mySerializedSVG])
  const url = urlObject.createObjectURL(export_blob)

  const a = document.createElement('a')
  let name = sessionStorage.getItem("areaName")
  a.setAttribute('download', name + '.svg')
  a.setAttribute('href', url)
  const evt = document.createEvent('MouseEvents')
  evt.initEvent('click', true, true)
  a.dispatchEvent(evt)
}`

clearRect改进的小建议

image

clearRect 放大后出现了一点错位,
我测试的canvas是允许透明的,
clearRect 清空的区域是否应该也是透明的

node-canvas 这个库生成的svg效果挺好的
看看能否为你的改进提供一些帮助

image
image

<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" viewBox="0 0 100 100">
<defs>
<filter id="filter-remove-color-and-invert-alpha" x="0%" y="0%" width="100%" height="100%">
<feColorMatrix color-interpolation-filters="sRGB" values="0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 -1 1"/>
</filter>
<filter id="filter-0" x="0%" y="0%" width="100%" height="100%">
<feImage xlink:href="#compositing-group-1" result="source" x="0" y="0" width="120" height="120"/>
<feImage xlink:href="#compositing-group-2" result="destination" x="0" y="0" width="120" height="120"/>
<feComposite in="source" in2="destination" operator="arithmetic" k1="0" k2="1" k3="1" k4="0" color-interpolation-filters="sRGB"/>
</filter>
<filter id="filter-1" x="0%" y="0%" width="100%" height="100%">
<feImage xlink:href="#compositing-group-4" result="source" x="0" y="0" width="120" height="120"/>
<feImage xlink:href="#compositing-group-5" result="destination" x="0" y="0" width="120" height="120"/>
<feComposite in="source" in2="destination" operator="arithmetic" k1="0" k2="1" k3="1" k4="0" color-interpolation-filters="sRGB"/>
</filter>
<g>
<g id="glyph-0-0">
<path d="M 3.75 0 L 3.75 -22.5 L 26.25 -22.5 L 26.25 0 Z M 5.625 -1.875 L 24.375 -1.875 L 24.375 -20.625 L 5.625 -20.625 Z M 5.625 -1.875 "/>
</g>
<g id="glyph-0-1">
<path d="M -0.148438 0 L 7.207031 -21.8125 L 10.78125 -21.8125 L 18.132812 0 L 15.074219 0 L 13.09375 -6.09375 L 4.761719 -6.09375 L 2.78125 0 Z M 12.289062 -8.570312 L 8.921875 -18.851562 L 5.566406 -8.570312 Z M 12.289062 -8.570312 "/>
</g>
<g id="glyph-0-2">
<path d="M 17.007812 -6.695312 C 17.003906 -5.609375 16.796875 -4.652344 16.390625 -3.824219 C 15.976562 -2.992188 15.425781 -2.308594 14.734375 -1.773438 C 13.914062 -1.125 13.035156 -0.667969 12.101562 -0.402344 C 11.160156 -0.132812 9.949219 0 8.46875 0 L 2.210938 0 L 2.210938 -21.8125 L 8 -21.8125 C 9.546875 -21.808594 10.710938 -21.757812 11.492188 -21.65625 C 12.265625 -21.554688 13.011719 -21.3125 13.726562 -20.933594 C 14.503906 -20.511719 15.074219 -19.960938 15.4375 -19.285156 C 15.796875 -18.601562 15.976562 -17.804688 15.980469 -16.890625 C 15.976562 -15.863281 15.707031 -14.945312 15.167969 -14.136719 C 14.625 -13.324219 13.875 -12.6875 12.921875 -12.230469 L 12.921875 -12.113281 C 14.214844 -11.757812 15.222656 -11.117188 15.9375 -10.1875 C 16.648438 -9.253906 17.003906 -8.089844 17.007812 -6.695312 Z M 12.964844 -16.480469 C 12.960938 -17.003906 12.871094 -17.460938 12.699219 -17.847656 C 12.519531 -18.234375 12.238281 -18.539062 11.851562 -18.765625 C 11.378906 -19.027344 10.855469 -19.1875 10.28125 -19.246094 C 9.703125 -19.304688 8.90625 -19.335938 7.894531 -19.335938 L 5.113281 -19.335938 L 5.113281 -12.949219 L 8.40625 -12.949219 C 9.3125 -12.949219 9.980469 -12.992188 10.414062 -13.085938 C 10.839844 -13.175781 11.285156 -13.371094 11.75 -13.667969 C 12.183594 -13.949219 12.496094 -14.320312 12.683594 -14.78125 C 12.867188 -15.238281 12.960938 -15.804688 12.964844 -16.480469 Z M 13.988281 -6.578125 C 13.984375 -7.394531 13.867188 -8.070312 13.636719 -8.605469 C 13.398438 -9.136719 12.925781 -9.589844 12.21875 -9.960938 C 11.753906 -10.203125 11.253906 -10.359375 10.714844 -10.429688 C 10.171875 -10.496094 9.402344 -10.527344 8.40625 -10.53125 L 5.113281 -10.53125 L 5.113281 -2.476562 L 7.46875 -2.476562 C 8.738281 -2.472656 9.738281 -2.53125 10.472656 -2.652344 C 11.199219 -2.765625 11.84375 -3.015625 12.40625 -3.398438 C 12.949219 -3.777344 13.351562 -4.207031 13.605469 -4.695312 C 13.859375 -5.175781 13.984375 -5.804688 13.988281 -6.578125 Z M 13.988281 -6.578125 "/>
</g>
<g id="glyph-0-3">
<path d="M 10.738281 0.394531 C 9.308594 0.390625 7.996094 0.15625 6.800781 -0.320312 C 5.601562 -0.796875 4.570312 -1.511719 3.707031 -2.460938 C 2.835938 -3.40625 2.160156 -4.585938 1.683594 -6.003906 C 1.203125 -7.417969 0.964844 -9.042969 0.96875 -10.882812 C 0.964844 -12.707031 1.199219 -14.300781 1.664062 -15.660156 C 2.125 -17.015625 2.800781 -18.195312 3.691406 -19.203125 C 4.558594 -20.175781 5.585938 -20.921875 6.78125 -21.4375 C 7.96875 -21.949219 9.304688 -22.207031 10.78125 -22.207031 C 11.511719 -22.207031 12.195312 -22.152344 12.835938 -22.042969 C 13.472656 -21.933594 14.066406 -21.796875 14.617188 -21.636719 C 15.082031 -21.484375 15.5625 -21.300781 16.058594 -21.085938 C 16.550781 -20.863281 17.039062 -20.621094 17.519531 -20.359375 L 17.519531 -16.859375 L 17.285156 -16.859375 C 17.03125 -17.089844 16.703125 -17.375 16.304688 -17.707031 C 15.902344 -18.039062 15.414062 -18.367188 14.839844 -18.691406 C 14.28125 -18.992188 13.675781 -19.238281 13.019531 -19.4375 C 12.363281 -19.628906 11.605469 -19.726562 10.75 -19.730469 C 9.820312 -19.726562 8.941406 -19.539062 8.113281 -19.160156 C 7.28125 -18.777344 6.554688 -18.214844 5.933594 -17.476562 C 5.3125 -16.730469 4.832031 -15.796875 4.496094 -14.675781 C 4.152344 -13.550781 3.984375 -12.285156 3.984375 -10.882812 C 3.984375 -9.382812 4.164062 -8.097656 4.527344 -7.023438 C 4.886719 -5.941406 5.378906 -5.03125 6.007812 -4.292969 C 6.609375 -3.566406 7.324219 -3.019531 8.144531 -2.65625 C 8.964844 -2.289062 9.832031 -2.109375 10.75 -2.109375 C 11.589844 -2.109375 12.367188 -2.210938 13.078125 -2.417969 C 13.789062 -2.621094 14.421875 -2.878906 14.984375 -3.195312 C 15.515625 -3.492188 15.980469 -3.804688 16.375 -4.125 C 16.761719 -4.441406 17.070312 -4.710938 17.300781 -4.9375 L 17.519531 -4.9375 L 17.519531 -1.480469 C 17.039062 -1.25 16.585938 -1.035156 16.164062 -0.832031 C 15.738281 -0.628906 15.222656 -0.429688 14.617188 -0.234375 C 13.980469 -0.03125 13.390625 0.125 12.851562 0.234375 C 12.304688 0.339844 11.601562 0.390625 10.738281 0.394531 Z M 10.738281 0.394531 "/>
</g>
</g>
<g id="compositing-group-0" transform="translate(10, 10)">
<rect x="-10" y="-10" width="120" height="120" fill="rgb(0%, 0%, 0%)" fill-opacity="0"/>
<path fill-rule="nonzero" fill="rgb(100%, 100%, 100%)" fill-opacity="1" d="M 0 0 L 10 0 L 10 10 L 0 10 Z M 0 0 "/>
</g>
<mask id="mask-0">
<use xlink:href="#compositing-group-0"/>
</mask>
<mask id="mask-1">
<use xlink:href="#compositing-group-0" filter="url(#filter-remove-color-and-invert-alpha)"/>
</mask>
<g id="compositing-group-1" mask="url(#mask-0)">
<g transform="translate(10, 10)">
</g>
</g>
<g id="compositing-group-2" mask="url(#mask-1)">
<g transform="translate(10, 10)">
<rect x="-10" y="-10" width="120" height="120" fill="rgb(0%, 0%, 0%)" fill-opacity="1"/>
<g fill="rgb(100%, 100%, 100%)" fill-opacity="1">
<use xlink:href="#glyph-0-1" x="30" y="29.999023"/>
<use xlink:href="#glyph-0-2" x="47.988281" y="29.999023"/>
<use xlink:href="#glyph-0-3" x="65.81543" y="29.999023"/>
</g>
</g>
</g>
<g id="compositing-group-3" transform="translate(10, 10)">
<rect x="-10" y="-10" width="120" height="120" fill="rgb(0%, 0%, 0%)" fill-opacity="0"/>
<path fill-rule="nonzero" fill="rgb(100%, 100%, 100%)" fill-opacity="1" d="M 0 0 L 44 0 L 44 44 L 0 44 Z M 0 0 "/>
</g>
<mask id="mask-2">
<use xlink:href="#compositing-group-3"/>
</mask>
<mask id="mask-3">
<use xlink:href="#compositing-group-3" filter="url(#filter-remove-color-and-invert-alpha)"/>
</mask>
<g id="compositing-group-4" mask="url(#mask-2)">
<g transform="translate(10, 10)">
</g>
</g>
<g id="compositing-group-5" mask="url(#mask-3)">
<g transform="translate(10, 10)">
<g filter="url(#filter-0)" transform="translate(-10, -10)">
<rect x="0" y="0" width="120" height="120" fill="rgb(0%, 0%, 0%)" fill-opacity="1"/>
</g>
</g>
</g>
</defs>
<g filter="url(#filter-1)" transform="translate(-10, -10)">
<rect x="0" y="0" width="120" height="120" fill="rgb(0%, 0%, 0%)" fill-opacity="1"/>
</g>
</svg>

arcTo does not work

This is the code.
let size=500;
let x1=0;
let x2=size/2;
let x3=size;
let y1=size/32;
let y3=size/3
2;
let y2=size/2;

ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.arcTo(x2, y2, x3, y3, 200);
ctx.lineTo(x3, y3);
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.lineTo(x3, y3);
ctx.stroke();

image

React Native support?

The example does not work in React Native because the document object is not available. Is there a workaround?

Code:

import { Context } from "svgcanvas";

export default () => {
  const ctx = new Context(500, 500); // Error occurs here
}

Error:

ERROR  ReferenceError: Property 'document' doesn't exist

This error is located at:
   in _default (created by _default)
   in RCTSafeAreaView (created by _default)
   in _default (created by _default)
   in _default
   in RCTView (created by View)
   in View (created by AppContainer)
   in RCTView (created by View)
   in View (created by AppContainer)
   in AppContainer
   in TestSvg(RootComponent), js engine: hermes

Versions:

    "react": "18.2.0",
    "react-native": "0.71.3",
    "svgcanvas": "^2.5.0"

Drawing in Canvas and SVG Simultaneously

I made a small modification to the canvas2svg.js code so that it works with ChartJS, it is rendering the SVG correctly but the rendering on Canvas is compromised, as can be seen in the posted image. Could it be that I can't use the canvas and SVG used by canvas2svg simultaneously?

what I would like is for the drawing to be done in the SVG and on the canvas simultaneously without problems

current result

image

example using Chart.js 2.6.0

 void renderChart() {
    
    var ctxC = canvas!.context2D;

    var c2Ss = C2S(C2SOptions(
      ctx: ctxC,
      canvas: canvas,
    ));

    final labels = items.map((e) => e['nom_situacao']).toList();
    final total = items.map((e) => e['total']).toList();

    final data = LinearChartData(labels: labels, datasets: <ChartDataSets>[
      ChartDataSets(
          // pointRadius: 5,
          //  borderRadius:5,
          label: 'processos por situacao',
          backgroundColor: FlatColor.generate2(
              length: total.length, inverse: false), //'#a009ed',
          data: total)
    ]);

    final config = ChartConfiguration(
        type: 'pie',
        data: data,
        options: ChartOptions(
          responsive: true,
          maintainAspectRatio: false,
          legend: ChartLegendOptions(display: true),
        ));

    Chart(c2Ss, config);

    Future.delayed(Duration(milliseconds: 1000), () {
      print('result SVG ${c2Ss.getSerializedSvg()}');
    });
  }

changed "svgcanvas" code to include calls to the original CanvasRenderingContext2D so it can draw on the canvas at the same time as creating the SVG

; (function () {
    "use strict";

    var STYLES, ctx, CanvasGradient, CanvasPattern, namedEntities;


    //helper function to format a string
    function format(str, args) {
        var keys = Object.keys(args), i;
        for (i = 0; i < keys.length; i++) {
            str = str.replace(new RegExp("\\{" + keys[i] + "\\}", "gi"), args[keys[i]]);
        }
        return str;
    }

    //helper function that generates a random string
    function randomString(holder) {
        var chars, randomstring, i;
        if (!holder) {
            throw new Error("cannot create a random attribute name for an undefined object");
        }
        chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
        randomstring = "";
        do {
            randomstring = "";
            for (i = 0; i < 12; i++) {
                randomstring += chars[Math.floor(Math.random() * chars.length)];
            }
        } while (holder[randomstring]);
        return randomstring;
    }

    //helper function to map named to numbered entities
    function createNamedToNumberedLookup(items, radix) {
        var i, entity, lookup = {}, base10, base16;
        items = items.split(',');
        radix = radix || 10;
        // Map from named to numbered entities.
        for (i = 0; i < items.length; i += 2) {
            entity = '&' + items[i + 1] + ';';
            base10 = parseInt(items[i], radix);
            lookup[entity] = '&#' + base10 + ';';
        }
        //FF and IE need to create a regex from hex values ie &nbsp; == \xa0
        lookup["\\xa0"] = '&#160;';
        return lookup;
    }

    //helper function to map canvas-textAlign to svg-textAnchor
    function getTextAnchor(textAlign) {
        //TODO: support rtl languages
        var mapping = { "left": "start", "right": "end", "center": "middle", "start": "start", "end": "end" };
        return mapping[textAlign] || mapping.start;
    }

    //helper function to map canvas-textBaseline to svg-dominantBaseline
    function getDominantBaseline(textBaseline) {
        //INFO: not supported in all browsers
        var mapping = { "alphabetic": "alphabetic", "hanging": "hanging", "top": "text-before-edge", "bottom": "text-after-edge", "middle": "central" };
        return mapping[textBaseline] || mapping.alphabetic;
    }

    // Unpack entities lookup where the numbers are in radix 32 to reduce the size
    // entity mapping courtesy of tinymce
    namedEntities = createNamedToNumberedLookup(
        '50,nbsp,51,iexcl,52,cent,53,pound,54,curren,55,yen,56,brvbar,57,sect,58,uml,59,copy,' +
        '5a,ordf,5b,laquo,5c,not,5d,shy,5e,reg,5f,macr,5g,deg,5h,plusmn,5i,sup2,5j,sup3,5k,acute,' +
        '5l,micro,5m,para,5n,middot,5o,cedil,5p,sup1,5q,ordm,5r,raquo,5s,frac14,5t,frac12,5u,frac34,' +
        '5v,iquest,60,Agrave,61,Aacute,62,Acirc,63,Atilde,64,Auml,65,Aring,66,AElig,67,Ccedil,' +
        '68,Egrave,69,Eacute,6a,Ecirc,6b,Euml,6c,Igrave,6d,Iacute,6e,Icirc,6f,Iuml,6g,ETH,6h,Ntilde,' +
        '6i,Ograve,6j,Oacute,6k,Ocirc,6l,Otilde,6m,Ouml,6n,times,6o,Oslash,6p,Ugrave,6q,Uacute,' +
        '6r,Ucirc,6s,Uuml,6t,Yacute,6u,THORN,6v,szlig,70,agrave,71,aacute,72,acirc,73,atilde,74,auml,' +
        '75,aring,76,aelig,77,ccedil,78,egrave,79,eacute,7a,ecirc,7b,euml,7c,igrave,7d,iacute,7e,icirc,' +
        '7f,iuml,7g,eth,7h,ntilde,7i,ograve,7j,oacute,7k,ocirc,7l,otilde,7m,ouml,7n,divide,7o,oslash,' +
        '7p,ugrave,7q,uacute,7r,ucirc,7s,uuml,7t,yacute,7u,thorn,7v,yuml,ci,fnof,sh,Alpha,si,Beta,' +
        'sj,Gamma,sk,Delta,sl,Epsilon,sm,Zeta,sn,Eta,so,Theta,sp,Iota,sq,Kappa,sr,Lambda,ss,Mu,' +
        'st,Nu,su,Xi,sv,Omicron,t0,Pi,t1,Rho,t3,Sigma,t4,Tau,t5,Upsilon,t6,Phi,t7,Chi,t8,Psi,' +
        't9,Omega,th,alpha,ti,beta,tj,gamma,tk,delta,tl,epsilon,tm,zeta,tn,eta,to,theta,tp,iota,' +
        'tq,kappa,tr,lambda,ts,mu,tt,nu,tu,xi,tv,omicron,u0,pi,u1,rho,u2,sigmaf,u3,sigma,u4,tau,' +
        'u5,upsilon,u6,phi,u7,chi,u8,psi,u9,omega,uh,thetasym,ui,upsih,um,piv,812,bull,816,hellip,' +
        '81i,prime,81j,Prime,81u,oline,824,frasl,88o,weierp,88h,image,88s,real,892,trade,89l,alefsym,' +
        '8cg,larr,8ch,uarr,8ci,rarr,8cj,darr,8ck,harr,8dl,crarr,8eg,lArr,8eh,uArr,8ei,rArr,8ej,dArr,' +
        '8ek,hArr,8g0,forall,8g2,part,8g3,exist,8g5,empty,8g7,nabla,8g8,isin,8g9,notin,8gb,ni,8gf,prod,' +
        '8gh,sum,8gi,minus,8gn,lowast,8gq,radic,8gt,prop,8gu,infin,8h0,ang,8h7,and,8h8,or,8h9,cap,8ha,cup,' +
        '8hb,int,8hk,there4,8hs,sim,8i5,cong,8i8,asymp,8j0,ne,8j1,equiv,8j4,le,8j5,ge,8k2,sub,8k3,sup,8k4,' +
        'nsub,8k6,sube,8k7,supe,8kl,oplus,8kn,otimes,8l5,perp,8m5,sdot,8o8,lceil,8o9,rceil,8oa,lfloor,8ob,' +
        'rfloor,8p9,lang,8pa,rang,9ea,loz,9j0,spades,9j3,clubs,9j5,hearts,9j6,diams,ai,OElig,aj,oelig,b0,' +
        'Scaron,b1,scaron,bo,Yuml,m6,circ,ms,tilde,802,ensp,803,emsp,809,thinsp,80c,zwnj,80d,zwj,80e,lrm,' +
        '80f,rlm,80j,ndash,80k,mdash,80o,lsquo,80p,rsquo,80q,sbquo,80s,ldquo,80t,rdquo,80u,bdquo,810,dagger,' +
        '811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro', 32);


    //Some basic mappings for attributes and default values.
    STYLES = {
        "strokeStyle": {
            svgAttr: "stroke", //corresponding svg attribute
            canvas: "#000000", //canvas default
            svg: "none",       //svg default
            apply: "stroke"    //apply on stroke() or fill()
        },
        "fillStyle": {
            svgAttr: "fill",
            canvas: "#000000",
            svg: null, //svg default is black, but we need to special case this to handle canvas stroke without fill
            apply: "fill"
        },
        "lineCap": {
            svgAttr: "stroke-linecap",
            canvas: "butt",
            svg: "butt",
            apply: "stroke"
        },
        "lineJoin": {
            svgAttr: "stroke-linejoin",
            canvas: "miter",
            svg: "miter",
            apply: "stroke"
        },
        "miterLimit": {
            svgAttr: "stroke-miterlimit",
            canvas: 10,
            svg: 4,
            apply: "stroke"
        },
        "lineWidth": {
            svgAttr: "stroke-width",
            canvas: 1,
            svg: 1,
            apply: "stroke"
        },
        "globalAlpha": {
            svgAttr: "opacity",
            canvas: 1,
            svg: 1,
            apply: "fill stroke"
        },
        "font": {
            //font converts to multiple svg attributes, there is custom logic for this
            canvas: "10px sans-serif"
        },
        "shadowColor": {
            canvas: "#000000"
        },
        "shadowOffsetX": {
            canvas: 0
        },
        "shadowOffsetY": {
            canvas: 0
        },
        "shadowBlur": {
            canvas: 0
        },
        "textAlign": {
            canvas: "start"
        },
        "textBaseline": {
            canvas: "alphabetic"
        },
        "lineDash": {
            svgAttr: "stroke-dasharray",
            canvas: [],
            svg: null,
            apply: "stroke"
        }
    };

    /**
     *
     * @param gradientNode - reference to the gradient
     * @constructor
     */
    CanvasGradient = function (gradientNode, ctx) {
        this.__root = gradientNode;
        this.__ctx = ctx;
    };

    /**
     * Adds a color stop to the gradient root
     */
    CanvasGradient.prototype.addColorStop = function (offset, color) {
        var stop = this.__ctx.__createElement("stop"), regex, matches;
        stop.setAttribute("offset", offset);
        if (color.indexOf("rgba") !== -1) {
            //separate alpha value, since webkit can't handle it
            regex = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?\.?\d*)\s*\)/gi;
            matches = regex.exec(color);
            stop.setAttribute("stop-color", format("rgb({r},{g},{b})", { r: matches[1], g: matches[2], b: matches[3] }));
            stop.setAttribute("stop-opacity", matches[4]);
        } else {
            stop.setAttribute("stop-color", color);
        }
        this.__root.appendChild(stop);
    };

    CanvasPattern = function (pattern, ctx) {
        this.__root = pattern;
        this.__ctx = ctx;
    };

    /**
     * The mock canvas context
     * @param o - options include:
     * ctx - existing Context2D to wrap around
     * width - width of your canvas (defaults to 500)
     * height - height of your canvas (defaults to 500)
     * enableMirroring - enables canvas mirroring (get image data) (defaults to false)
     * document - the document object (defaults to the current document)
     */
    ctx = function (o) {
        var defaultOptions = { width: 500, height: 500, enableMirroring: false }, options;

        //keep support for this way of calling C2S: new C2S(width,height)
        if (arguments.length > 1) {
            options = defaultOptions;
            options.width = arguments[0];
            options.height = arguments[1];
        } else if (!o) {
            options = defaultOptions;
        } else {
            options = o;
        }

        if (!(this instanceof ctx)) {
            //did someone call this without new?
            return new ctx(options);
        }

        //setup options
        this.width = options.width || defaultOptions.width;
        this.height = options.height || defaultOptions.height;
        this.enableMirroring = options.enableMirroring !== undefined ? options.enableMirroring : defaultOptions.enableMirroring;

        this.canvas = this;   ///point back to this instance!
        this.__document = options.document || document;

        // allow passing in an existing context to wrap around
        // if a context is passed in, we know a canvas already exist
        if (options.ctx) {
            this.__ctx = options.ctx;
            this.__canvas = options.canvas;
        } else {
            // this.__canvas = this.__document.createElement("canvas");
            // this.__ctx = this.__canvas.getContext("2d");
        }

        this.__setDefaultStyles();
        this.__stack = [this.__getStyleState()];
        this.__groupStack = [];

        //the root svg element
        this.__root = this.__document.createElementNS("http://www.w3.org/2000/svg", "svg");
        this.__root.setAttribute("version", 1.1);
        this.__root.setAttribute("xmlns", "http://www.w3.org/2000/svg");
        this.__root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
        this.__root.setAttribute("width", this.width);
        this.__root.setAttribute("height", this.height);

        //make sure we don't generate the same ids in defs
        this.__ids = {};

        //defs tag
        this.__defs = this.__document.createElementNS("http://www.w3.org/2000/svg", "defs");
        this.__root.appendChild(this.__defs);

        //also add a group child. the svg element can't use the transform attribute
        this.__currentElement = this.__document.createElementNS("http://www.w3.org/2000/svg", "g");
        this.__root.appendChild(this.__currentElement);
    };

    // Object.defineProperty(ctx.prototype, "fillStyle", {
    //     get: function fillStyle() {
    //     }
    // });

    // isaque adicionou isso para funcionar com ChartJS
    ctx.prototype.__defineGetter__("fillStyle", function () {
        //console.log('ctx.prototype.__defineGetter__');
        return this._fillStyle;
    });
    ctx.prototype.__defineSetter__("fillStyle", function (val) {
        //console.log(`ctx.prototype.__defineSetter ${val}`);
        this.__ctx.fillStyle = val;
        this._fillStyle = val;
    });
    ctx.prototype.__defineGetter__("strokeStyle", function () {
        return this._strokeStyle;
    });
    ctx.prototype.__defineSetter__("strokeStyle", function (val) {
        this.__ctx.strokeStyle = val;
        this._strokeStyle = val;
    });
    ctx.prototype.__defineGetter__("lineCap", function () {
        return this._lineCap;
    });
    ctx.prototype.__defineSetter__("lineCap", function (val) {
        this.__ctx.lineCap = val;
        this._lineCap = val;
    });
    ctx.prototype.__defineGetter__("lineJoin", function () {
        return this._lineJoin;
    });
    ctx.prototype.__defineSetter__("lineJoin", function (val) {
        this.__ctx.lineJoin = val;
        this._lineJoin = val;
    });
    ctx.prototype.__defineGetter__("miterLimit", function () {
        return this._miterLimit;
    });
    ctx.prototype.__defineSetter__("miterLimit", function (val) {
        this.__ctx.miterLimit = val;
        this._miterLimit = val;
    });
    ctx.prototype.__defineGetter__("lineWidth", function () {
        return this._lineWidth;
    });
    ctx.prototype.__defineSetter__("lineWidth", function (val) {
        this.__ctx.lineWidth = val;
        this._lineWidth = val;
    });
    ctx.prototype.__defineGetter__("globalAlpha", function () {
        return this._globalAlpha;
    });
    ctx.prototype.__defineSetter__("globalAlpha", function (val) {
        this.__ctx.globalAlpha = val;
        this._globalAlpha = val;
    });
    ctx.prototype.__defineGetter__("textAlign", function () {
        return this._textAlign;
    });
    ctx.prototype.__defineSetter__("textAlign", function (val) {
        this.__ctx.textAlign = val;
        this._textAlign = val;
    });

    ctx.prototype.__defineGetter__("parentNode", function () {
        return this.__canvas.parentNode;
    });


    /**
     * Creates the specified svg element
     * @private
     */
    ctx.prototype.__createElement = function (elementName, properties, resetFill) {
        if (typeof properties === "undefined") {
            properties = {};
        }

        var element = this.__document.createElementNS("http://www.w3.org/2000/svg", elementName),
            keys = Object.keys(properties), i, key;
        if (resetFill) {
            //if fill or stroke is not specified, the svg element should not display. By default SVG's fill is black.
            element.setAttribute("fill", "none");
            element.setAttribute("stroke", "none");
        }
        for (i = 0; i < keys.length; i++) {
            key = keys[i];
            element.setAttribute(key, properties[key]);
        }
        return element;
    };

    /**
     * Applies default canvas styles to the context
     * @private
     */
    ctx.prototype.__setDefaultStyles = function () {
        //console.log(`ctx.prototype.__setDefaultStyles `);
        //default 2d canvas context properties see:http://www.w3.org/TR/2dcontext/
        var keys = Object.keys(STYLES), i, key;
        for (i = 0; i < keys.length; i++) {
            key = keys[i];
            this[key] = STYLES[key].canvas;
            //console.log(`ctx.prototype.__setDefaultStyles ${key} ${this[key]}`);
        }
    };

    /**
     * Applies styles on restore
     * @param styleState
     * @private
     */
    ctx.prototype.__applyStyleState = function (styleState) {
        // console.log(`ctx.prototype.__applyStyleState`);
        var keys = Object.keys(styleState), i, key;
        for (i = 0; i < keys.length; i++) {
            key = keys[i];
            this[key] = styleState[key];
        }
    };

    /**
     * Gets the current style state
     * @return {Object}
     * @private
     */
    ctx.prototype.__getStyleState = function () {
        // console.log(`ctx.prototype.__getStyleState`);
        var i, styleState = {}, keys = Object.keys(STYLES), key;
        for (i = 0; i < keys.length; i++) {
            key = keys[i];
            styleState[key] = this[key];
        }
        return styleState;
    };

    /**
     * Apples the current styles to the current SVG element. On "ctx.fill" or "ctx.stroke"
     * @param type
     * @private
     */
    ctx.prototype.__applyStyleToCurrentElement = function (type) {
        //console.log(`ctx.prototype.__applyStyleToCurrentElement ${type}`);

        var currentElement = this.__currentElement;
        var currentStyleGroup = this.__currentElementsToStyle;
        if (currentStyleGroup) {
            currentElement.setAttribute(type, "");
            currentElement = currentStyleGroup.element;
            currentStyleGroup.children.forEach(function (node) {
                node.setAttribute(type, "");
            })
        }

        var keys = Object.keys(STYLES), i, style, value, id, regex, matches;
        for (i = 0; i < keys.length; i++) {
            style = STYLES[keys[i]];
            value = this[keys[i]];
            // console.log(`ctx.prototype.__applyStyleToCurrentElement value ${keys[i]} ${value}`);
            if (style.apply) {
                //is this a gradient or pattern?
                if (value instanceof CanvasPattern) {
                    //pattern
                    if (value.__ctx) {
                        //copy over defs
                        while (value.__ctx.__defs.childNodes.length) {
                            id = value.__ctx.__defs.childNodes[0].getAttribute("id");
                            this.__ids[id] = id;
                            this.__defs.appendChild(value.__ctx.__defs.childNodes[0]);
                        }
                    }
                    currentElement.setAttribute(style.apply, format("url(#{id})", { id: value.__root.getAttribute("id") }));
                }
                else if (value instanceof CanvasGradient) {
                    //gradient
                    currentElement.setAttribute(style.apply, format("url(#{id})", { id: value.__root.getAttribute("id") }));
                } else if (style.apply.indexOf(type) !== -1 && style.svg !== value) {
                    if ((style.svgAttr === "stroke" || style.svgAttr === "fill") && value.indexOf("rgba") !== -1) {
                        //separate alpha value, since illustrator can't handle it
                        regex = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?\.?\d*)\s*\)/gi;
                        matches = regex.exec(value);
                        currentElement.setAttribute(style.svgAttr, format("rgb({r},{g},{b})", { r: matches[1], g: matches[2], b: matches[3] }));
                        //should take globalAlpha here
                        var opacity = matches[4];
                        var globalAlpha = this.globalAlpha;
                        if (globalAlpha != null) {
                            opacity *= globalAlpha;
                        }
                        currentElement.setAttribute(style.svgAttr + "-opacity", opacity);
                    } else {
                        var attr = style.svgAttr;
                        if (keys[i] === 'globalAlpha') {
                            attr = type + '-' + style.svgAttr;
                            if (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
                        currentElement.setAttribute(attr, value);
                    }
                }
            }
        }
    };

    /**
     * Will return the closest group or svg node. May return the current element.
     * @private
     */
    ctx.prototype.__closestGroupOrSvg = function (node) {
        node = node || this.__currentElement;
        if (node.nodeName === "g" || node.nodeName === "svg") {
            return node;
        } else {
            return this.__closestGroupOrSvg(node.parentNode);
        }
    };


    /**
     * Returns the serialized value of the svg so far
     * @param fixNamedEntities - Standalone SVG doesn't support named entities, which document.createTextNode encodes.
     *                           If true, we attempt to find all named entities and encode it as a numeric entity.
     * @return serialized svg
     */
    ctx.prototype.getSerializedSvg = function (fixNamedEntities) {
        var serialized = new XMLSerializer().serializeToString(this.__root),
            keys, i, key, value, regexp, xmlns;

        //IE search for a duplicate xmnls because they didn't implement setAttributeNS correctly
        xmlns = /xmlns="http:\/\/www\.w3\.org\/2000\/svg".+xmlns="http:\/\/www\.w3\.org\/2000\/svg/gi;
        if (xmlns.test(serialized)) {
            serialized = serialized.replace('xmlns="http://www.w3.org/2000/svg', 'xmlns:xlink="http://www.w3.org/1999/xlink');
        }

        if (fixNamedEntities) {
            keys = Object.keys(namedEntities);
            //loop over each named entity and replace with the proper equivalent.
            for (i = 0; i < keys.length; i++) {
                key = keys[i];
                value = namedEntities[key];
                regexp = new RegExp(key, "gi");
                if (regexp.test(serialized)) {
                    serialized = serialized.replace(regexp, value);
                }
            }
        }

        return serialized;
    };


    /**
     * Returns the root svg
     * @return
     */
    ctx.prototype.getSvg = function () {
        return this.__root;
    };
    /**
     * Will generate a group tag.
     */
    ctx.prototype.save = function () {
        var group = this.__createElement("g");
        var parent = this.__closestGroupOrSvg();
        this.__groupStack.push(parent);
        parent.appendChild(group);
        this.__currentElement = group;
        this.__stack.push(this.__getStyleState());
    };
    /**
     * Sets current element to parent, or just root if already root
     */
    ctx.prototype.restore = function () {
        this.__currentElement = this.__groupStack.pop();
        this.__currentElementsToStyle = null;
        //Clearing canvas will make the poped group invalid, currentElement is set to the root group node.
        if (!this.__currentElement) {
            this.__currentElement = this.__root.childNodes[1];
        }
        var state = this.__stack.pop();
        this.__applyStyleState(state);
    };

    /**
     * Helper method to add transform
     * @private
     */
    ctx.prototype.__addTransform = function (t) {
        //if the current element has siblings, add another group
        var parent = this.__closestGroupOrSvg();
        if (parent.childNodes.length > 0) {
            if (this.__currentElement.nodeName === "path") {
                if (!this.__currentElementsToStyle) this.__currentElementsToStyle = { element: parent, children: [] };
                this.__currentElementsToStyle.children.push(this.__currentElement)
                this.__applyCurrentDefaultPath();
            }

            var group = this.__createElement("g");
            parent.appendChild(group);
            this.__currentElement = group;
        }

        var transform = this.__currentElement.getAttribute("transform");
        if (transform) {
            transform += " ";
        } else {
            transform = "";
        }
        transform += t;
        this.__currentElement.setAttribute("transform", transform);
    };

    /**
     *  scales the current element
     */
    ctx.prototype.scale = function (x, y) {

        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.scale(x, y);
        }

        if (y === undefined) {
            y = x;
        }
        this.__addTransform(format("scale({x},{y})", { x: x, y: y }));
    };

    /**
     * rotates the current element
     */
    ctx.prototype.rotate = function (angle) {

        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.rotate(angle);
        }

        var degrees = (angle * 180 / Math.PI);
        this.__addTransform(format("rotate({angle},{cx},{cy})", { angle: degrees, cx: 0, cy: 0 }));
    };

    /**
     * translates the current element
     */
    ctx.prototype.translate = function (x, y) {

        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.translate(x, y);
        }

        this.__addTransform(format("translate({x},{y})", { x: x, y: y }));
    };

    /**
     * applies a transform to the current element
     */
    ctx.prototype.transform = function (a, b, c, d, e, f) {

        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.transform(a, b, c, d, e, f);
        }

        this.__addTransform(format("matrix({a},{b},{c},{d},{e},{f})", { a: a, b: b, c: c, d: d, e: e, f: f }));
    };

    /**
     * Create a new Path Element
     */
    ctx.prototype.beginPath = function () {

        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.beginPath();
        }

        var path, parent;

        // Note that there is only one current default path, it is not part of the drawing state.
        // See also: https://html.spec.whatwg.org/multipage/scripting.html#current-default-path
        this.__currentDefaultPath = "";
        this.__currentPosition = {};

        path = this.__createElement("path", {}, true);
        parent = this.__closestGroupOrSvg();
        parent.appendChild(path);
        this.__currentElement = path;
    };

    /**
     * Helper function to apply currentDefaultPath to current path element
     * @private
     */
    ctx.prototype.__applyCurrentDefaultPath = function () {
        var currentElement = this.__currentElement;
        if (currentElement.nodeName === "path") {
            currentElement.setAttribute("d", this.__currentDefaultPath);
        } else {
            console.error("Attempted to apply path command to node", currentElement.nodeName);
        }
    };

    /**
     * Helper function to add path command
     * @private
     */
    ctx.prototype.__addPathCommand = function (command) {
        this.__currentDefaultPath += " ";
        this.__currentDefaultPath += command;
    };

    /**
     * Adds the move command to the current path element,
     * if the currentPathElement is not empty create a new path element
     */
    ctx.prototype.moveTo = function (x, y) {
        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.moveTo(x, y);
        }

        if (this.__currentElement.nodeName !== "path") {
            this.beginPath();
        }

        // creates a new subpath with the given point
        this.__currentPosition = { x: x, y: y };
        this.__addPathCommand(format("M {x} {y}", { x: x, y: y }));
    };

    /**
     * Closes the current path
     */
    ctx.prototype.closePath = function () {

        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.closePath();
        }

        if (this.__currentDefaultPath) {
            this.__addPathCommand("Z");
        }
    };

    /**
     * Adds a line to command
     */
    ctx.prototype.lineTo = function (x, y) {

        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.lineTo(x, y);
        }

        this.__currentPosition = { x: x, y: y };
        if (this.__currentDefaultPath.indexOf('M') > -1) {
            this.__addPathCommand(format("L {x} {y}", { x: x, y: y }));
        } else {
            this.__addPathCommand(format("M {x} {y}", { x: x, y: y }));
        }
    };

    /**
     * Add a bezier command
     */
    ctx.prototype.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {

        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
        }

        this.__currentPosition = { x: x, y: y };
        this.__addPathCommand(format("C {cp1x} {cp1y} {cp2x} {cp2y} {x} {y}",
            { cp1x: cp1x, cp1y: cp1y, cp2x: cp2x, cp2y: cp2y, x: x, y: y }));
    };

    /**
     * Adds a quadratic curve to command
     */
    ctx.prototype.quadraticCurveTo = function (cpx, cpy, x, y) {

        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.quadraticCurveTo(cpx, cpy, x, y);
        }

        this.__currentPosition = { x: x, y: y };
        this.__addPathCommand(format("Q {cpx} {cpy} {x} {y}", { cpx: cpx, cpy: cpy, x: x, y: y }));
    };


    /**
     * Return a new normalized vector of given vector
     */
    var normalize = function (vector) {

        var len = Math.sqrt(vector[0] * vector[0] + vector[1] * vector[1]);
        return [vector[0] / len, vector[1] / len];
    };

    /**
     * Adds the arcTo to the current path
     *
     * @see http://www.w3.org/TR/2015/WD-2dcontext-20150514/#dom-context-2d-arcto
     */
    ctx.prototype.arcTo = function (x1, y1, x2, y2, radius) {

        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.arcTo(x1, y1, x2, y2, radius);
        }

        // Let the point (x0, y0) be the last point in the subpath.
        var x0 = this.__currentPosition && this.__currentPosition.x;
        var y0 = this.__currentPosition && this.__currentPosition.y;

        // First ensure there is a subpath for (x1, y1).
        if (typeof x0 == "undefined" || typeof y0 == "undefined") {
            return;
        }

        // Negative values for radius must cause the implementation to throw an IndexSizeError exception.
        if (radius < 0) {
            throw new Error("IndexSizeError: The radius provided (" + radius + ") is negative.");
        }

        // If the point (x0, y0) is equal to the point (x1, y1),
        // or if the point (x1, y1) is equal to the point (x2, y2),
        // or if the radius radius is zero,
        // then the method must add the point (x1, y1) to the subpath,
        // and connect that point to the previous point (x0, y0) by a straight line.
        if (((x0 === x1) && (y0 === y1))
            || ((x1 === x2) && (y1 === y2))
            || (radius === 0)) {
            this.lineTo(x1, y1);
            return;
        }

        // Otherwise, if the points (x0, y0), (x1, y1), and (x2, y2) all lie on a single straight line,
        // then the method must add the point (x1, y1) to the subpath,
        // and connect that point to the previous point (x0, y0) by a straight line.
        var unit_vec_p1_p0 = normalize([x0 - x1, y0 - y1]);
        var unit_vec_p1_p2 = normalize([x2 - x1, y2 - y1]);
        if (unit_vec_p1_p0[0] * unit_vec_p1_p2[1] === unit_vec_p1_p0[1] * unit_vec_p1_p2[0]) {
            this.lineTo(x1, y1);
            return;
        }

        // Otherwise, let The Arc be the shortest arc given by circumference of the circle that has radius radius,
        // and that has one point tangent to the half-infinite line that crosses the point (x0, y0) and ends at the point (x1, y1),
        // 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).
        // The points at which this circle touches these two lines are called the start and end tangent points respectively.

        // note that both vectors are unit vectors, so the length is 1
        var cos = (unit_vec_p1_p0[0] * unit_vec_p1_p2[0] + unit_vec_p1_p0[1] * unit_vec_p1_p2[1]);
        var theta = Math.acos(Math.abs(cos));

        // Calculate origin
        var unit_vec_p1_origin = normalize([
            unit_vec_p1_p0[0] + unit_vec_p1_p2[0],
            unit_vec_p1_p0[1] + unit_vec_p1_p2[1]
        ]);
        var len_p1_origin = radius / Math.sin(theta / 2);
        var x = x1 + len_p1_origin * unit_vec_p1_origin[0];
        var y = y1 + len_p1_origin * unit_vec_p1_origin[1];

        // Calculate start angle and end angle
        // rotate 90deg clockwise (note that y axis points to its down)
        var unit_vec_origin_start_tangent = [
            -unit_vec_p1_p0[1],
            unit_vec_p1_p0[0]
        ];
        // rotate 90deg counter clockwise (note that y axis points to its down)
        var unit_vec_origin_end_tangent = [
            unit_vec_p1_p2[1],
            -unit_vec_p1_p2[0]
        ];
        var getAngle = function (vector) {
            // get angle (clockwise) between vector and (1, 0)
            var x = vector[0];
            var y = vector[1];
            if (y >= 0) { // note that y axis points to its down
                return Math.acos(x);
            } else {
                return -Math.acos(x);
            }
        };
        var startAngle = getAngle(unit_vec_origin_start_tangent);
        var endAngle = getAngle(unit_vec_origin_end_tangent);

        // Connect the point (x0, y0) to the start tangent point by a straight line
        this.lineTo(x + unit_vec_origin_start_tangent[0] * radius,
            y + unit_vec_origin_start_tangent[1] * radius);

        // Connect the start tangent point to the end tangent point by arc
        // and adding the end tangent point to the subpath.
        this.arc(x, y, radius, startAngle, endAngle);
    };

    /**
     * Sets the stroke property on the current element
     */
    ctx.prototype.stroke = function () {
        // console.log('ctx.prototype.stroke');
        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.stroke();
        }

        if (this.__currentElement.nodeName === "path") {
            this.__currentElement.setAttribute("paint-order", "fill stroke markers");
        }
        this.__applyCurrentDefaultPath();
        this.__applyStyleToCurrentElement("stroke");
    };

    /**
     * Sets fill properties on the current element
     */
    ctx.prototype.fill = function () {
        // console.log('ctx.prototype.fill');
        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.fill();
        }

        if (this.__currentElement.nodeName === "path") {
            this.__currentElement.setAttribute("paint-order", "stroke fill markers");
        }
        this.__applyCurrentDefaultPath();
        this.__applyStyleToCurrentElement("fill");
    };

    /**
     *  Adds a rectangle to the path.
     */
    ctx.prototype.rect = function (x, y, width, height) {

        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.rect(x, y, width, height);
        }

        if (this.__currentElement.nodeName !== "path") {
            this.beginPath();
        }
        this.moveTo(x, y);
        this.lineTo(x + width, y);
        this.lineTo(x + width, y + height);
        this.lineTo(x, y + height);
        this.lineTo(x, y);
        this.closePath();
    };


    /**
     * adds a rectangle element
     */
    ctx.prototype.fillRect = function (x, y, width, height) {
        // console.log(' ctx.prototype.fillRect ');
        // console.log(this.__ctx.fillStyle);
        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.fillRect(x, y, width, height);
        }

        var rect, parent;
        rect = this.__createElement("rect", {
            x: x,
            y: y,
            width: width,
            height: height
        }, true);
        parent = this.__closestGroupOrSvg();
        parent.appendChild(rect);
        this.__currentElement = rect;
        this.__applyStyleToCurrentElement("fill");
    };

    /**
     * Draws a rectangle with no fill
     * @param x
     * @param y
     * @param width
     * @param height
     */
    ctx.prototype.strokeRect = function (x, y, width, height) {

        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.strokeRect(x, y, width, height);
        }

        var rect, parent;
        rect = this.__createElement("rect", {
            x: x,
            y: y,
            width: width,
            height: height
        }, true);
        parent = this.__closestGroupOrSvg();
        parent.appendChild(rect);
        this.__currentElement = rect;
        this.__applyStyleToCurrentElement("stroke");
    };


    /**
     * Clear entire canvas:
     * 1. save current transforms
     * 2. remove all the childNodes of the root g element
     */
    ctx.prototype.__clearCanvas = function () {
        //console.log('ctx.prototype.__clearCanvas');

        var current = this.__closestGroupOrSvg(),
            transform = current.getAttribute("transform");
        var rootGroup = this.__root.childNodes[1];
        var childNodes = rootGroup.childNodes;
        for (var i = childNodes.length - 1; i >= 0; i--) {
            if (childNodes[i]) {
                rootGroup.removeChild(childNodes[i]);
            }
        }
        this.__currentElement = rootGroup;
        //reset __groupStack as all the child group nodes are all removed.
        this.__groupStack = [];
        if (transform) {
            this.__addTransform(transform);
        }
    };

    /**
     * "Clears" a canvas by just drawing a white rectangle in the current group.
     */
    ctx.prototype.clearRect = function (x, y, width, height) {
        //console.log('ctx.prototype.clearRect');

        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.clearRect(x, y, width, height);
        }

        //clear entire canvas
        if (x === 0 && y === 0 && width === this.width && height === this.height) {
            this.__clearCanvas();
            return;
        }
        var rect, parent = this.__closestGroupOrSvg();
        rect = this.__createElement("rect", {
            x: x,
            y: y,
            width: width,
            height: height,
            fill: "#FFFFFF"
        }, true);
        parent.appendChild(rect);
    };

    /**
     * Adds a linear gradient to a defs tag.
     * Returns a canvas gradient object that has a reference to it's parent def
     */
    ctx.prototype.createLinearGradient = function (x1, y1, x2, y2) {

        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.createLinearGradient(x1, y1, x2, y2);
        }

        var grad = this.__createElement("linearGradient", {
            id: randomString(this.__ids),
            x1: x1 + "px",
            x2: x2 + "px",
            y1: y1 + "px",
            y2: y2 + "px",
            "gradientUnits": "userSpaceOnUse"
        }, false);
        this.__defs.appendChild(grad);
        return new CanvasGradient(grad, this);
    };

    /**
     * Adds a radial gradient to a defs tag.
     * Returns a canvas gradient object that has a reference to it's parent def
     */
    ctx.prototype.createRadialGradient = function (x0, y0, r0, x1, y1, r1) {

        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.createRadialGradient(x0, y0, r0, x1, y1, r1);
        }

        var grad = this.__createElement("radialGradient", {
            id: randomString(this.__ids),
            cx: x1 + "px",
            cy: y1 + "px",
            r: r1 + "px",
            fx: x0 + "px",
            fy: y0 + "px",
            "gradientUnits": "userSpaceOnUse"
        }, false);
        this.__defs.appendChild(grad);
        return new CanvasGradient(grad, this);

    };

    /**
     * Parses the font string and returns svg mapping
     * @private
     */
    ctx.prototype.__parseFont = function () {
        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;
        var fontPart = regex.exec(this.font);
        var data = {
            style: fontPart[1] || 'normal',
            size: fontPart[4] || '10px',
            family: fontPart[6] || 'sans-serif',
            weight: fontPart[3] || 'normal',
            decoration: fontPart[2] || 'normal',
            href: null
        };

        //canvas doesn't support underline natively, but we can pass this attribute
        if (this.__fontUnderline === "underline") {
            data.decoration = "underline";
        }

        //canvas also doesn't support linking, but we can pass this as well
        if (this.__fontHref) {
            data.href = this.__fontHref;
        }

        return data;
    };

    /**
     * Helper to link text fragments
     * @param font
     * @param element
     * @return {*}
     * @private
     */
    ctx.prototype.__wrapTextLink = function (font, element) {
        if (font.href) {
            var a = this.__createElement("a");
            a.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", font.href);
            a.appendChild(element);
            return a;
        }
        return element;
    };

    /**
     * Fills or strokes text
     * @param text
     * @param x
     * @param y
     * @param action - stroke or fill
     * @private
     */
    ctx.prototype.__applyText = function (text, x, y, action) {
        var font = this.__parseFont(),
            parent = this.__closestGroupOrSvg(),
            textElement = this.__createElement("text", {
                "font-family": font.family,
                "font-size": font.size,
                "font-style": font.style,
                "font-weight": font.weight,
                "text-decoration": font.decoration,
                "x": x,
                "y": y,
                "text-anchor": getTextAnchor(this.textAlign),
                "dominant-baseline": getDominantBaseline(this.textBaseline)
            }, true);

        textElement.appendChild(this.__document.createTextNode(text));
        this.__currentElement = textElement;
        this.__applyStyleToCurrentElement(action);
        parent.appendChild(this.__wrapTextLink(font, textElement));
    };

    /**
     * Creates a text element
     * @param text
     * @param x
     * @param y
     */
    ctx.prototype.fillText = function (text, x, y) {
        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.fillText(text, x, y);
        }

        this.__applyText(text, x, y, "fill");
    };

    /**
     * Strokes text
     * @param text
     * @param x
     * @param y
     */
    ctx.prototype.strokeText = function (text, x, y) {
        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.fillText(strokeText, x, y);
        }

        this.__applyText(text, x, y, "stroke");
    };

    /**
     * No need to implement this for svg.
     * @param text
     * @return {TextMetrics}
     */
    ctx.prototype.measureText = function (text) {



        this.__ctx.font = this.font;
        return this.__ctx.measureText(text);
    };

    /**
     *  Arc command!
     */
    ctx.prototype.arc = function (x, y, radius, startAngle, endAngle, counterClockwise) {

        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.arc(x, y, radius, startAngle, endAngle, counterClockwise);
        }

        // in canvas no circle is drawn if no angle is provided.
        if (startAngle === endAngle) {
            return;
        }
        startAngle = startAngle % (2 * Math.PI);
        endAngle = endAngle % (2 * Math.PI);
        if (startAngle === endAngle) {
            //circle time! subtract some of the angle so svg is happy (svg elliptical arc can't draw a full circle)
            endAngle = ((endAngle + (2 * Math.PI)) - 0.001 * (counterClockwise ? -1 : 1)) % (2 * Math.PI);
        }
        var endX = x + radius * Math.cos(endAngle),
            endY = y + radius * Math.sin(endAngle),
            startX = x + radius * Math.cos(startAngle),
            startY = y + radius * Math.sin(startAngle),
            sweepFlag = counterClockwise ? 0 : 1,
            largeArcFlag = 0,
            diff = endAngle - startAngle;

        // https://github.com/gliffy/canvas2svg/issues/4
        if (diff < 0) {
            diff += 2 * Math.PI;
        }

        if (counterClockwise) {
            largeArcFlag = diff > Math.PI ? 0 : 1;
        } else {
            largeArcFlag = diff > Math.PI ? 1 : 0;
        }

        this.lineTo(startX, startY);
        this.__addPathCommand(format("A {rx} {ry} {xAxisRotation} {largeArcFlag} {sweepFlag} {endX} {endY}",
            { rx: radius, ry: radius, xAxisRotation: 0, largeArcFlag: largeArcFlag, sweepFlag: sweepFlag, endX: endX, endY: endY }));

        this.__currentPosition = { x: endX, y: endY };
    };

    /**
     * Generates a ClipPath from the clip command.
     */
    ctx.prototype.clip = function () {

        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.clip();
        }


        var group = this.__closestGroupOrSvg(),
            clipPath = this.__createElement("clipPath"),
            id = randomString(this.__ids),
            newGroup = this.__createElement("g");

        this.__applyCurrentDefaultPath();
        group.removeChild(this.__currentElement);
        clipPath.setAttribute("id", id);
        clipPath.appendChild(this.__currentElement);

        this.__defs.appendChild(clipPath);

        //set the clip path to this group
        group.setAttribute("clip-path", format("url(#{id})", { id: id }));

        //clip paths can be scaled and transformed, we need to add another wrapper group to avoid later transformations
        // to this path
        group.appendChild(newGroup);

        this.__currentElement = newGroup;

    };

    /**
     * Draws a canvas, image or mock context to this canvas.
     * Note that all svg dom manipulation uses node.childNodes rather than node.children for IE support.
     * http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-drawimage
     */
    ctx.prototype.drawImage = function () {



        //convert arguments to a real array
        var args = Array.prototype.slice.call(arguments),
            image = args[0],
            dx, dy, dw, dh, sx = 0, sy = 0, sw, sh, parent, svg, defs, group,
            currentElement, svgImage, canvas, context, id;

        if (args.length === 3) {
            dx = args[1];
            dy = args[2];
            sw = image.width;
            sh = image.height;
            dw = sw;
            dh = sh;
        } else if (args.length === 5) {
            dx = args[1];
            dy = args[2];
            dw = args[3];
            dh = args[4];
            sw = image.width;
            sh = image.height;
        } else if (args.length === 9) {
            sx = args[1];
            sy = args[2];
            sw = args[3];
            sh = args[4];
            dx = args[5];
            dy = args[6];
            dw = args[7];
            dh = args[8];
        } else {
            throw new Error("Invalid number of arguments passed to drawImage: " + arguments.length);
        }

        parent = this.__closestGroupOrSvg();
        currentElement = this.__currentElement;
        var translateDirective = "translate(" + dx + ", " + dy + ")";
        if (image instanceof ctx) {
            //canvas2svg mock canvas context. In the future we may want to clone nodes instead.
            //also I'm currently ignoring dw, dh, sw, sh, sx, sy for a mock context.
            svg = image.getSvg().cloneNode(true);
            if (svg.childNodes && svg.childNodes.length > 1) {
                defs = svg.childNodes[0];
                while (defs.childNodes.length) {
                    id = defs.childNodes[0].getAttribute("id");
                    this.__ids[id] = id;
                    this.__defs.appendChild(defs.childNodes[0]);
                }
                group = svg.childNodes[1];
                if (group) {
                    //save original transform
                    var originTransform = group.getAttribute("transform");
                    var transformDirective;
                    if (originTransform) {
                        transformDirective = originTransform + " " + translateDirective;
                    } else {
                        transformDirective = translateDirective;
                    }
                    group.setAttribute("transform", transformDirective);
                    parent.appendChild(group);
                }
            }
        } else if (image.nodeName === "CANVAS" || image.nodeName === "IMG") {
            //canvas or image
            svgImage = this.__createElement("image");
            svgImage.setAttribute("width", dw);
            svgImage.setAttribute("height", dh);
            svgImage.setAttribute("preserveAspectRatio", "none");

            if (sx || sy || sw !== image.width || sh !== image.height) {
                //crop the image using a temporary canvas
                canvas = this.__document.createElement("canvas");
                canvas.width = dw;
                canvas.height = dh;
                context = canvas.getContext("2d");
                context.drawImage(image, sx, sy, sw, sh, 0, 0, dw, dh);
                image = canvas;
            }
            svgImage.setAttribute("transform", translateDirective);
            svgImage.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href",
                image.nodeName === "CANVAS" ? image.toDataURL() : image.getAttribute("src"));
            parent.appendChild(svgImage);
        }
    };

    /**
     * Generates a pattern tag
     */
    ctx.prototype.createPattern = function (image, repetition) {

        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.createPattern(image, repetition);
        }

        var pattern = this.__document.createElementNS("http://www.w3.org/2000/svg", "pattern"), id = randomString(this.__ids),
            img;
        pattern.setAttribute("id", id);
        pattern.setAttribute("width", image.width);
        pattern.setAttribute("height", image.height);
        if (image.nodeName === "CANVAS" || image.nodeName === "IMG") {
            img = this.__document.createElementNS("http://www.w3.org/2000/svg", "image");
            img.setAttribute("width", image.width);
            img.setAttribute("height", image.height);
            img.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href",
                image.nodeName === "CANVAS" ? image.toDataURL() : image.getAttribute("src"));
            pattern.appendChild(img);
            this.__defs.appendChild(pattern);
        } else if (image instanceof ctx) {
            pattern.appendChild(image.__root.childNodes[1]);
            this.__defs.appendChild(pattern);
        }
        return new CanvasPattern(pattern, this);
    };

    ctx.prototype.setLineDash = function (dashArray) {

        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.setLineDash(dashArray);
        }

        if (dashArray && dashArray.length > 0) {
            this.lineDash = dashArray.join(",");
        } else {
            this.lineDash = null;
        }
    };

    /* Chart JS v4.2.1 Compatibility */
    ctx.prototype.getContext = function (contextId) {
        if (String(contextId).toUpperCase() === '2D') {
            return this
        }
        return null
    }
    ctx.prototype.getContext2d = function () {
        return this.__ctx;
    }
    ctx.prototype.style = function () {
        //console.log('ctx.prototype.style');
        // console.log(this.__canvas.style);
        return this.__canvas.style;
    }
    ctx.prototype.getAttribute = function (prop_name) {
        return this[prop_name]
    }



    /**
     * Not yet implemented
     */
    ctx.prototype.drawFocusRing = function () {
        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.drawFocusRing();
        }
    };
    ctx.prototype.createImageData = function () {
        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.createImageData();
        }
    };
    ctx.prototype.getImageData = function () {
        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.getImageData();
        }
    };
    ctx.prototype.putImageData = function () {
        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.putImageData();
        }
    };
    ctx.prototype.globalCompositeOperation = function () {
        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.globalCompositeOperation();
        }
    };

    /**
     * SetTransform changes the current transformation matrix to
     * the matrix given by the arguments as described below.
     *
     * @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setTransform
     */
    ctx.prototype.setTransform = function (a, b, c, d, e, f) {

        //isaque adicionou
        if (this.__ctx) {
            this.__ctx.setTransform(a, b, c, d, e, f);
        }

        if (a instanceof DOMMatrix) {
            this.__transformMatrix = new DOMMatrix([a.a, a.b, a.c, a.d, a.e, a.f]);
        } else {
            this.__transformMatrix = new DOMMatrix([a, b, c, d, e, f]);
        }
    };

    /**
     * GetTransform Returns a copy of the current transformation matrix,
     * as a newly created DOMMAtrix Object
     *
     * @returns A DOMMatrix Object
     */
    ctx.prototype.getTransform = function () {
        //isaque adicionou
        if (this.__ctx) {
            return this.__ctx.getTransform();
        }

        let { a, b, c, d, e, f } = this.__transformMatrix;
        return new DOMMatrix([a, b, c, d, e, f]);
    };

    /**
     * ResetTransform resets the current transformation matrix to the identity matrix
     *
     * @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/resetTransform
     */
    ctx.prototype.resetTransform = function () {
        //isaque adicionou
        if (this.__ctx) {
            return this.__ctx.resetTransform();
        }

        this.setTransform(1, 0, 0, 1, 0, 0);
    };

    // ctx.prototype.resetTransform = function () { };
    ctx.prototype.addEventListener = function (type, listener, eventListenerOptions) { };

    //add options for alternative namespace
    if (typeof window === "object") {
        window.C2S = ctx;
    }

    // CommonJS/Browserify
    if (typeof module === "object" && typeof module.exports === "object") {
        module.exports = ctx;
    }

}());

Calling `Context.fill` with a path does not work

The Canvas API supports passing a Path2D object to fill and stroke. This is not handled by svgcanvas.

Unfortunately it doesn't look like it could be easily supported since there is no way to extract the path definition from the Path2D object.

One approach might be to mock the Path2D object too so that the calls that construct the path can be recorded.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.