JSFiddle - React, Tailwind, and code Playground
by Slava
HTML
<canvas id="sourceCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">Your browser does not support the HTML5 canvas tag.</canvas>
<div id="output"></div>
JavaScript
const sourceCanvas = document.getElementById('sourceCanvas');
// Drawing test content to source canvas
sourceCanvas.getContext('2d').fillStyle = 'red';
sourceCanvas.getContext('2d').fillRect(0,0,150,75);
// Create new SVG element
var SVG = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
SVG.setAttribute('style', 'border: 1px solid black;');
SVG.setAttribute('width', '600');
SVG.setAttribute('height', '400');
SVG.setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:xlink','http://www.w3.org/1999/xlink');
// Function: Add data to SVG
function importCanvas(sourceCanvas, targetSVG){
// get base64 encoded png data url from Canvas
var img_dataurl = sourceCanvas.toDataURL('image/png');
var svg_img = document.createElementNS("http://www.w3.org/2000/svg", "image");
svg_img.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', img_dataurl);
jQuery(targetSVG.appendChild( svg_img)).appendTo('#graph-container');
console.log( 'done' ); // Log & confirm
}
importCanvas(sourceCanvas, SVG);
// Convert canvas from HTML5 to 'cansvas-svg' object ---------------------------
//var newCanvas = new CanvasSVG.Deferred();
//newCanvas.wrapCanvas(sourceCanvas);
//var newCanvas.getContext('2d') = sourceCanvas.getContext('2d');
//drawCanvasContent(canvasContext);
// Conversion to SVG --------------------------------------------
//var canvas2DContent = sourceCanvas.getContext("2d");
//var SVG = sourceCanvas.getContext('2d').getSVG();
var SVG = newCanvasSVGContext.getSVG();
// Output
document.getElementById('output').appendChild(SVG);