-
Notifications
You must be signed in to change notification settings - Fork 115
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
d48eae4
commit f502ce4
Showing
1 changed file
with
76 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
<!DOCTYPE html> | ||
<html> | ||
<head lang="en"> | ||
<meta charset="UTF-8"> | ||
<title>demo</title> | ||
<style> | ||
body { | ||
font: 10px sans-serif; | ||
} | ||
.content { | ||
width: 550px; | ||
margin: 100px auto; | ||
} | ||
</style> | ||
</head> | ||
<body> | ||
<div class="content"> | ||
<div id="playground"></div> | ||
<div> | ||
<button id="render-as-image">Render as image</button> | ||
</div> | ||
<img id="as-img" style="display: block"></img> | ||
</div> | ||
|
||
<script src="function-plot.js"></script> | ||
|
||
<script> | ||
const loadImage = async url => { | ||
const $img = document.createElement('img') | ||
$img.src = url | ||
return new Promise((resolve, reject) => { | ||
$img.onload = () => resolve($img) | ||
$img.onerror = reject | ||
}) | ||
} | ||
|
||
// renderToImg renders a SVG node to an img node. | ||
// source https://stackoverflow.com/a/74026755/3341726 | ||
async function renderToImg() { | ||
const dataHeader = 'data:image/svg+xml;charset=utf-8' | ||
const serializeAsXML = e => (new XMLSerializer()).serializeToString(e) | ||
const encodeAsUTF8 = s => `${dataHeader},${encodeURIComponent(s)}` | ||
|
||
const svg = document.querySelector("#playground svg") | ||
const svgData = encodeAsUTF8(serializeAsXML(svg)) | ||
const img = await loadImage(svgData) | ||
|
||
const canvas = document.createElement('canvas') | ||
canvas.width = svg.clientWidth | ||
canvas.height = svg.clientHeight | ||
canvas.getContext('2d').drawImage(img, 0, 0, svg.clientWidth, svg.clientHeight) | ||
|
||
const dataURL = await canvas.toDataURL(`image/png`, 1.0) | ||
document.querySelector('#as-img').src = dataURL | ||
} | ||
|
||
// initial render | ||
functionPlot({ | ||
target: '#playground', | ||
data: [ | ||
{ | ||
fn: 'x^2', | ||
graphType: 'polyline', | ||
} | ||
] | ||
}) | ||
|
||
// Button listener to trigger renderToImg | ||
document.querySelector('#render-as-image').addEventListener('click', async function () { | ||
await renderToImg() | ||
}) | ||
|
||
</script> | ||
|
||
</body> | ||
</html> |