Last active
April 15, 2024 16:30
-
-
Save quartorz/8b466e885aa4f71876f8a23a8f89a6c2 to your computer and use it in GitHub Desktop.
mermaid.jsの図をpngで保存する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>Mermaid.js</title> | |
<script src="https://cdn.jsdelivr.net/npm/mermaid@10.2.3/dist/mermaid.min.js"></script> | |
</head> | |
<body> | |
<div id="container"> | |
<div class="split"> | |
<textarea id="input"></textarea> | |
<button id="save">Save</button> | |
</div> | |
<div id="result" class="split"> | |
</div> | |
</div> | |
<style> | |
body { | |
margin: 0; | |
} | |
#container { | |
display: flex; | |
flex-direction: row; | |
} | |
.split { | |
flex: 1; | |
height: 100vh; | |
} | |
#input { | |
height: calc(100vh - 30px); | |
width: 100%; | |
} | |
#save { | |
height: 30px; | |
width: 100%; | |
} | |
#result { | |
overflow: scroll; | |
} | |
</style> | |
<script> | |
mermaid.initialize(); | |
/** @type {HTMLTextAreaElement} */ | |
const input = document.getElementById('input'); | |
const save = document.getElementById('save'); | |
const result = document.getElementById('result'); | |
let timeoutId; | |
input.addEventListener('keydown', () => { | |
clearInterval(timeoutId); | |
timeoutId = setTimeout(async () => { | |
const prevScrollTop = result.scrollTop; | |
result.innerHTML = (await mermaid.render('graphDiv', input.value)).svg; | |
result.scrollTop = prevScrollTop; | |
}, 100); | |
}); | |
save.addEventListener('click', () => { | |
// SVGの読み込み | |
var svg = document.getElementById('graphDiv'); | |
var svgData = new XMLSerializer().serializeToString(svg); | |
// canvasの描画 | |
var canvas = document.createElement("canvas"); | |
canvas.width = svg.width.baseVal.value; | |
canvas.height = svg.height.baseVal.value; | |
var ctx = canvas.getContext("2d"); | |
var data = svgData; | |
var DOMURL = self.URL || self.webkitURL || self; | |
var img = new Image(); | |
var svg = new Blob([data], { | |
type: "image/svg+xml" | |
}); | |
var url = DOMURL.createObjectURL(svg); | |
ctx.fillStyle = 'white'; | |
ctx.fillRect(0, 0, canvas.width, canvas.height); | |
img.onload = function() { | |
ctx.drawImage(img, 0, 0); | |
DOMURL.revokeObjectURL(url); | |
const pngUrl = canvas.toDataURL('image/png'); | |
const a = document.createElement('a'); | |
a.href = pngUrl; | |
a.download = 'mermaid.png'; | |
document.body.appendChild(a); | |
a.click(); | |
document.body.removeChild(a); | |
}; | |
img.src = url; | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment