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?
相关问题
- Convert svg to geojson fails with ogr2ogr
- How to get coordinates of an svg?
- Changing color of SVG which was embedded using <
- Understanding svg's viewbox attribute
- Convert an inline SVG into a SVG file
相关文章
- Make marker-end same color as path?
- How to display unicode in SVG?
- Converting svg to png with inkscape command line f
- How to create an SVG Matrix without an SVG element
- rect collision detection d3js
- My background image get cut off at the bottom
- Unwanted namespaces on SVG markup when using XMLSe
- D3 grouped bar chart: How to rotate the text of x
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).
In the HTML
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 theinnerHTML
nor theouterHTML
attributes are present on SVG elements in the current HTML standard.)<link rel="icon">
in your page's<head>
.In JavaScript
innerHTML
attribute of the HTML element you've wrapped it in, or by callingnew 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 theload
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 itssrc
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 ascanvasElement
) and set its dimensions (by settingcanvasElement.width = 64
andcanvasElement.height = 64
).canvasElement.getContext('2d')
(heretofore referred to asctx
).ctx.globalCompositeOperation = "copy"
, or clear it withctx.clearRect(0, 0, 64, 64)
.load
listener you added to the<img>
element you created in step 3, draw the image onto the canvas usingctx.drawImage(svgImg, 0, 0, 64, 64)
(wheresvgImg
is the<img>
element you set thesrc
to the SVG DataURL).canvasElement.toDataURL()
, and set that to thehref
attribute of the<link rel="icon">
element in your HTML.