1

I'm trying to get a generates SVG to draw inside a canvas. The code below works OK in Chrome, but not in Firefox.

<html> <body> <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" style="width: 100px; height; 100px"> <rect x="0" width="100" height="100" rx="15" fill="pink" /> <circle cx="50" cy="50" r="25"/> </svg> <canvas style="border: 1px dashed black; height: 100px; width: 100px"> </canvas> <script> const canvas = document.querySelector("canvas") const svg = document.querySelector("svg") const outerHTML = svg.cloneNode(true).outerHTML const blob = new Blob([outerHTML],{type:'image/svg+xml;charset=utf-8'}); let url = window.URL || window.webkitURL || window; let blobURL = url.createObjectURL(blob); const img = document.createElement("img") document.querySelector("body").appendChild(img) img.onload = () => { try { canvas.height = 100 canvas.width = 100 let ctx = canvas.getContext('2d'); ctx.fillRect(0,0,100,100); ctx.clearRect(10,20,30,40); ctx.drawImage(img, 0, 0, 100, 100); } catch(e) { console.log(e) } }; img.src = blobURL </script> </body> </html>

Everything appears to work here -- including the image loading -- except for the drawImage call. The small pink rounded-rect with the black circle is the SVG. The big one on the bottom is the same thing loaded into an img element. (The "0.5ms" is because this is being loaded via a Rails app but that's inconsequential)

screenshot

The dashed box is the canvas that I'm trying to draw into. The fillRect and clearRect work. I'm inside the onload, so I know the image has finished loading. The dimensions are all correct. The image is loaded into the img element, so I know the browser can handle the blob.

I don't know what else could be wrong here.

2
  • 1
    Thank you, that's a great clue. Now I know it works in Chrome but not Firefox. Commented Feb 11, 2021 at 19:21
  • Good call--I was able to reproduce so I'll edit that into the question. Commented Feb 11, 2021 at 19:29

1 Answer 1

1

Thanks to ggorlen's comment about the runnable snippet working, I tried this in Chrome and it worked. That led me down a new Googling path where I found this SO question from a while back stating that this exact problem could be solved by putting width and height attributes on the root <svg> element.

And, in fact, it did solve the problem!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.