JSFiddle - React, Tailwind, and code Playground
by unloco
HTML
<div id="content"></div>
<button id="toggle">Show/Hide canvas</button>
CSS
#content {
position: relative;
}
svg {
outline: 1px solid #eee;
}
canvas {
position: absolute;
top: 0;
left: 0;
outline: 1px solid red;
}
JavaScript
// this svg code is normally calculated dynamically
var svg_code = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -272 501 336" width="501" height="336">
<text font-size="300" font-family="'Arial'" fill="#f00" x="0" y="0" text-anchor="middle">
<tspan x="50%" dy="0">123</tspan>
</text>
</svg>`;
document.getElementById('content').innerHTML = svg_code;
var width = 501;
var height = 336;
var img = new Image();
img.src = "data:image/svg+xml; charset=utf8, " +
encodeURIComponent(svg_code.replace('fill="#f00"', 'fill="#0f0"'));
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.id = "canvas";
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
console.log(canvas);
console.log(ctx);
document.getElementById('content').appendChild(canvas);
}
// toggle button
document.getElementById('toggle').addEventListener('click', function() {
var canvas = document.getElementById("canvas");
var svg = document.getElementById("svg");
if (canvas.style.display === "none") {
canvas.style.display = "block";
svg.style.opacity = 0;
} else {
canvas.style.display = "none";
svg.style.opacity = 1;
}
});