SVG to Canvas
HTML
SVG
<svg viewBox="0 0 240 40">
<text x="10" y="30" class="small">
You are
<tspan fill='red'>n</tspan><tspan fill='blue'>o</tspan><tspan>t</tspan>
a banana!
</text>
</svg>
IMAGE
<img/>
CANVAS HIGH QUALITY
<canvas id="high"></canvas>
CANVAS LOW QUALITY
<canvas id="low"></canvas>
CSS
svg, img, canvas {
display: block;
}
JavaScript
var svg = document.querySelector('svg');
var img = document.querySelector('img');
var canvas = document.querySelector('#high');
var canvasLow = document.querySelector('#low');
// get svg data
var xml = new XMLSerializer().serializeToString(svg);
// make it base64
var svg64 = btoa(xml);
var b64Start = 'data:image/svg+xml;base64,';
// prepend a "header"
var image64 = b64Start + svg64;
function draw() {
// Make sure the canvas accommodates your monitor density!
canvas.width = img.width * window.devicePixelRatio;
canvas.height = img.height * window.devicePixelRatio;
canvas.style.width = `${img.width}px`;
canvas.style.height = `${img.height}px`;
let ctx = canvas.getContext('2d', {antialias: false});
ctx.mozImageSmoothingEnabled = false;
ctx.webkitImageSmoothingEnabled = false;
ctx.msImageSmoothingEnabled = false;
ctx.imageSmoothingEnabled = false;
ctx.drawImage(
img, 0, 0,
img.width * window.devicePixelRatio,
img.height * window.devicePixelRatio
);
canvasLow.width = img.width;
canvasLow.height = img.height;
ctx = canvasLow.getContext('2d', {antialias: false});
ctx.mozImageSmoothingEnabled = false;
ctx.webkitImageSmoothingEnabled = false;
ctx.msImageSmoothingEnabled = false;
ctx.imageSmoothingEnabled = false;
ctx.drawImage(img, 0, 0, img.width, img.height);
}
img.onload = draw;
img.src = image64;
if (img.width > 0) {
draw();
}