Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to render SVG elements directly in Svelte?

I am trying to import and render SVG's in Svelte.

I am using @rollup/plugin-url to import the SVG code like so:

<script>
  import arrowCircle from "heroicons/dist/solid-sm/sm-arrow-circle-up.svg"
</script>

<main>
  <object title="Arrow Circle" type="image/svg+xml" data={arrowCircle}></object>
</main>

Now this works (in terms of the SVG content getting brought in) but it renders the following screen:

Rendered SVG

Rendered SVG tag

Ideally I would like to use the <object /> element so I can apply classes to the SVG but given the error I thought I would have a go with the <img /> tag to see if this would at least render the SVG, but instead got this:

<img src="data:image/svg+xml,%3Csvg%20viewBox%3D%220%200%2020%2020%22%20fill%3D%22currentColor%22%3E%20%20%3Cpath%20fill-rule%3D%22evenodd%22%20d%3D%22M10%2018a8%208%200%20100-16%208%208%200%20000%2016zm3.707-8.707l-3-3a1%201%200%2000-1.414%200l-3%203a1%201%200%20001.414%201.414L9%209.414V13a1%201%200%20102%200V9.414l1.293%201.293a1%201%200%20001.414-1.414z%22%20clip-rule%3D%22evenodd%22%2F%3E%3C%2Fsvg%3E">

I also tried just {arrowCircle} but that rendered the above image src as plain text.

From what I can tell it is to do with the data prefix that is part of the raw import.

I am aware of the codefeathers/rollup-plugin-svelte-svg plugin but would like to be able to do be able to do this without another plugin if possible, or at least understand what is going on.

For reference SVG are valid in both <img /> tags as well as <object /> as per this article.

like image 439
Otis Wright Avatar asked Apr 27 '20 05:04

Otis Wright


People also ask

How do I render an SVG file?

The easiest way to render SVG files is to construct a QSvgWidget and load an SVG file using one of the QSvgWidget::load() functions.

Can you embed SVG elements directly into an HTML page?

You can embed SVG elements directly into your HTML pages.

What is the most appropriate way to make SVG picture accessible?

Using the <img> Tag For basic, uncomplicated, or decorative images, use the <img> tag and reference the SVG as a file. This pattern should render lighter and faster pages overall (versus inline SVGs) and allow for easier maintenance on SVGs that you use in multiple places.

How do I use icons in svelte?

Use something like https://github.com/cristovao-trevisan/svelte-icon or https://github.com/codefeathers/rollup-plugin-svelte-svg to directly import each icon into code: import Home from './icons/home. svg'; Create a svelte component that selects the right imported component or SVG string and displays it.


1 Answers

It looks as though the SVG file isn't valid as a standalone image. Try this:

<?xml version="1.0" encoding="utf-8"?>
<svg xmlns="http://www.w3.org/2000/svg" ...>...</svg>
like image 91
Rich Harris Avatar answered Oct 17 '22 07:10

Rich Harris