Our SVG viewer can have the next options:

  • An editor that enables us to jot down, paste, and edit SVG code
  • A validation mechanism that checks if the SVG Code is legitimate
  • A preview space the place we’ll see the SVG in real-time
  • An export function that may permit us to export the SVG

So, by the top of this tutorial, we’ll have one thing like this:

The SVG editor can have a textual content space so as to add, edit, or paste the SVG code.

1

class="editor">

2
   

class="editor-header">SVG Code Editor

3
   
4
      id="svgInput"
5
      placeholder="Paste your SVG code right here and watch the magic occur..."
6
      >
7

The preview space can have a preview container the place the present SVG code shall be injected for preview.

1

class="preview">

2
   

class="preview-header">SVG Preview

3
   

class="preview-content">

4
      

id="previewContainer" class="preview-container">

5
   
6

HTML Markup

Okay, let’s begin with the constructing blocks. The HTML markup will appear like this:

1

class="predominant">

2
  
3
    SVG Preview Device
4
    Edit, preview, and export clear, scalable vector artwork
5
  
6
  

class="container">

7
    

class="editor">

8
      

class="editor-header">SVG Code Editor

9
      
10
      
11
        id="svgInput"
12
        placeholder="Paste your SVG code right here and watch the magic occur..."
13
      >
14
      
15
    
16
    

class="preview">

17
      

class="preview-header">SVG Preview

18
      

class="preview-content">

19
        

id="previewContainer" class="preview-container">

20
      
21
    
22
  
23

24
  
25

Styling with CSS

As you noticed from the ultimate demo, we wish the editor and the preview to seem aspect by aspect on giant screens and stack vertically on small gadgets.  We’ll obtain this format utilizing Flexbox and media queries.  

Let’s start by making use of some primary kinds to the and

components as proven under.

1
@import url("https://fonts.googleapis.com/css2?household=DM+Mono:ital,wght@0,300;0,400;0,500;1,300;1,400;1,500&show=swap");
2

3
* {
4
  margin: 0;
5
  padding: 0;
6
  box-sizing: border-box;
7
}
8

9
physique {
10
  show: flex;
11
  min-height: 100vh;
12
  justify-content: middle;
13
  padding: 20px;
14
  font-family: "DM Mono", monospace;
15
}
16

17
header {
18
  max-width: 420px;
19
  text-align: middle;
20
  margin-bottom: 40px;
21
}
22

23
h1 {
24
  font-size: 30px;
25
  font-weight: 700;
26
  margin-bottom: 8px;
27
}
28

29
header p {
30
  font-size: 18px;
31
}

We’ll apply the next kinds to make sure all components are stacked vertically. 

1
.predominant {
2
  show: flex;
3
  flex-direction: column;
4
  align-items: middle;
5
  hole: 24px;
6
  width: 100%;
7
  max-width: 1000px;
8
  peak: 90vh;
9
  min-height: 700px;
10
  margin-top: 50px;
11
}
12
.container {
13
  show: flex;
14
  peak: calc(100% - 84px);
15
  hole: 20px;
16
  width: 100%;
17
}

We additionally need the textual content editor and the preview container to fill the accessible peak of their mum or dad containers.

1
.editor {
2
  border: 1px strong #7287f2;
3
}
4

5
.editor,
6
.preview {
7
  width: 50%;
8
  show: flex;
9
  flex-direction: column;
10
  border-radius: 16px;
11
  overflow: hidden;
12
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
13
}
14

15
.editor-header,
16
.preview-header {
17
  padding: 12px 20px;
18
  font-weight: 600;
19
  font-size: 14px;
20
  text-align: middle;
21
  width: 100%;
22
  coloration: white;
23

24
}
25

26
textarea {
27
  /* width: 100%; */
28
  peak: 100%;
29
  border: none;
30
  padding: 20px;
31
  font-size: 13px;
32
  resize: none;
33
  background: #2e3138;
34
  coloration: white;
35
  overflow-y: auto;
36
}
37

38
textarea:focus {
39
  define: none;
40
}
41

42
.preview-container {
43
  width: 100%;
44
  peak: 100%;
45
  border-radius: 16px;
46
  background-color: #f9fafb;
47
  overflow-y: auto;
48
}
49

50
.preview-content {
51
  flex: 1;
52
  padding: 16px;
53
  overflow: hidden;
54
}
55

56
.svg-container {
57
  show: flex;
58
  justify-content: middle;
59
  overflow: hidden;
60
}

Lastly, let’s type the export button, add kinds for displaying error messages, and apply media queries for responsiveness. 

1
.error-message {
2
  coloration: #dc2626;
3
  background: #fef2f2;
4
  border: 1px strong #fca5a5;
5
  padding: 16px;
6
  margin: 20px;
7
  border-radius: 6px;
8
  font-size: 13px;
9
}
10

11
button {
12
  margin-top: 40px;
13
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
14
  coloration: white;
15
  padding: 12px 30px;
16
  border: none;
17
  border-radius: 8px;
18
  cursor: pointer;
19
  width: 150px;
20
}
21

22
@media (max-width: 768px) {
23
  physique {
24
    padding: 20px;
25
  }
26

27
  .predominant {
28
    width: 100%;
29
    peak: 100vh;
30
  }
31

32
  .container {
33
    flex-direction: column;
34
    peak: 100%;
35
  }
36

37
  .editor,
38
  .preview {
39
    width: 100%;
40
    peak: 50%;
41
  }
42
}

Now the SVG  device interface seems like this:

Svg viewer ToolSvg viewer ToolSvg viewer Tool

JavaScript performance

On this part, we’ll carry out some SVG code validation to make sure that any SVG code added to the editor is parsed earlier than being displayed.

We’ll additionally add a pattern SVG code within the editor and show it within the preview space by default.

Let’s begin by getting the weather from the DOM and assigning them to variables for straightforward entry.

1
const svgInput = doc.getElementById("svgInput");
2
const previewContainer = doc.getElementById("previewContainer");
3
const exportBtn = doc.getElementById("exportBtn");

SVG Code Validation

The subsequent step is to make sure that the SVG code is legitimate earlier than including it for preview. Create a perform known as loadSVG() that takes an SVG string as an argument. 

Inside this perform, we are going to first examine if the SVG string is empty. If its empty, we’ll show an error message.

1
perform loadSVG(svgCode) {
2
previewContainer.innerHTML = "";
3
if (!svgCode.trim()) {
4
  showErrorMessage("Enter SVG code to see preview");
5
  return;
6
}}

The second type of validation shall be performed utilizing the DOMParser to make sure the SVG Code is nicely formatted XML code.

DOMParser is an inbuilt interface in JavaScript that enables us to transform XML or HTML strings right into a DOM Doc object. As soon as the string is parsed right into a DOM, you’ll be able to question it utilizing commonplace DOM strategies like querySelector, and many others. 

To parse the XML, first create an occasion of the DOMParser API. Then, parse the SVG string utilizing the ParseFromString() technique and set “picture/svg+xml” because the MIME kind.

1
const parser = new DOMParser();
2
const doc = parser.parseFromString(svgCode, "picture/svg+xml");

Verify for errors by querying the aspect. If there are not any errors, we are going to extract the aspect and inject it into the preview.

1
perform loadSVG(svgCode) {
2
    previewContainer.innerHTML = "";
3
    if (!svgCode.trim()) {
4
        showErrorMessage("Enter SVG code to see preview");
5
        return;
6
    }
7

8
    attempt {
9
        const parser = new DOMParser();
10
        const doc = parser.parseFromString(svgCode, "picture/svg+xml");
11
        const parserError = doc.querySelector("parsererror");
12
        if (parserError)
13
            throw new Error("XML parsing error: " + parserError.textContent);
14
        const svgElement = doc.querySelector("svg");
15
        if (!svgElement) throw new Error("No legitimate SVG aspect discovered");
16

17
        const container = doc.createElement("div");
18
        container.className = "svg-container";
19
        container.innerHTML = svgCode;
20
        previewContainer.appendChild(container);
21
    } catch (error) {
22

23
        showErrorMessage("Invalid SVG code: " + error.message);
24
    }
25
}

Add occasion listeners

We now have a perform that validates and shows the SVG code, so the following step is to make sure it runs earlier than the SVG code within the enter adjustments.

Add two occasion listeners to the textarea aspect as proven under:

1
svgInput.addEventListener("enter", perform () {
2
    loadSVG(this.worth);
3
  });
4
  svgInput.addEventListener("paste", perform () {
5
    loadSVG(this.worth);
6
  });

The enter occasion shall be triggered everytime you kind, delete, or change the contents of the  textual content space, whereas the paste occasion shall be triggered if you paste the content material to the textual content space.

Load pattern SVG and export SVG

The ultimate step is to make sure that now we have a default SVG when the device opens. That is nice to make sure the consumer sees how the device works. 

Create a perform known as loadDefaultSVG() which seems like this:

1
perform loadDefaultSVG() {
2
  const sampleSvg = `