Tag Archive SVG

Byphunsanit

Mermaid.js: Dynamic Render

อันนี้ลองเขียนดูแบบ ให้สามารถลองเขียน ลองเปลี่ยนตัว mermaid markup ได้ง่าย ๆ ถึงจะมี Mermaid Live Editor อยู่แต่ในการเขียน program การดึงมันจาก database หรือ API ต่าง ๆ แบบ dynamic render ออกมาเป็น SVG เป็นสิ่งที่ต้องใช้บ่อย ๆ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!DOCTYPE html>
<html>
 
<head>
    <meta charset="utf-8">
    <title>Mermaid: Dynamic Render</title>
</head>
 
<body>
 
    <a href="https://mermaid.js.org/intro/#diagram-types" target="_blank">Mermaid Diagram Types</a><br>
    <label for="exampleFormControlTextarea1">Here is a mermaid diagram:</label>
    <br>
    <textarea cols="100" id="sourceTa" rows="10">
pie title What Voldemort doesn't have?
"FRIENDS" : 2
"FAMILY" : 3
"NOSE" : 45</textarea>
    <br>
    <button id="submitBtn" type="button">Submit</button>
    <button id="resetBtn" type="button">Reset</button>
    <br>
    <svg id="previewSVG"></svg>
 
    <script type="module">
 
        mermaid.initialize({ startOnLoad: false })
     
        const sourceTa = document.getElementById('sourceTa');
        const previewSVG = document.getElementById('previewSVG');
 
        document.getElementById('resetBtn').onclick = function () {
            previewSVG.innerHTML = '';
        };
 
        document.getElementById('submitBtn').onclick = function () {
            mermaid.render('preview', sourceTa.value).then(({ svg }) => {
                previewSVG.innerHTML = svg;
            }).catch(error => {
                alert('Mermaid diagram error: ' + error.message);
            });
        };
    </script>
</body>
 
</html>

แค่ 2 บรรทัด

  1. mermaid.initialize({ startOnLoad: false }) บอก mermaid ว่าไม่ต้องทำงานก่อนนะ พักก่อน
  2. mermaid.render อันนี้ก็ตามชื่อเลย render ตาม markup ที่ป้อนเข้าไป แล้วคืนมาเป็น SVG