I have an SVG element on my page. I want to use it as the page's favicon. How do I do this in JavaScript?
Doing this is astoundingly convoluted. You can see my solution in action here: the methodology is described below (getting the HTML elements, by ID or otherwise, is left as an exercise for the reader).
xmlns="http://www.w3.org/2000/svg"
, as you're going to need to take the source of the element as its own file, and the XMLNS declaration is required for standalone SVG files. (Also note that this means your SVG will need to be self-contained and can't refer to elements in its parent document with something like <use>
.)<div>
or <span>
, which you may use to get the content of the <svg>
element using .innerHTML
. (Neither the innerHTML
nor the outerHTML
attributes are present on SVG elements in the current HTML standard.)<link rel="icon">
in your page's <head>
.innerHTML
attribute of the HTML element you've wrapped it in, or by calling new XMLSerializer().serializeToString()
on the SVG element."data:image/svg+xml,"
to the source. (If most browsers supported SVGs for favicons, we'd be done here, but since, at time of writing, they don't, we must go deeper.)<img>
element that you'll be routing the image through, add an event listener to it for the load
event that will draw the image once control returns to the event loop (as spec-compliant browsers won't let you read the image synchronously - see this crbug), and set the DataURL of your SVG source as its src
attribute. (The steps between this and step 8 can happen either in sync now, or as part of the listener callback; they just need to happen before you draw the image.)<canvas>
element (heretofore referred to as canvasElement
) and set its dimensions (by setting canvasElement.width = 64
and canvasElement.height = 64
).canvasElement.getContext('2d')
(heretofore referred to as ctx
).ctx.globalCompositeOperation = "copy"
, or clear it with ctx.clearRect(0, 0, 64, 64)
.load
listener you added to the <img>
element you created in step 3, draw the image onto the canvas using ctx.drawImage(svgImg, 0, 0, 64, 64)
(where svgImg
is the <img>
element you set the src
to the SVG DataURL).canvasElement.toDataURL()
, and set that to the href
attribute of the <link rel="icon">
element in your HTML.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With