英文:
Download SVG element from page when user clicks
问题
我创建了一个 Svelte 组件,它根据一些参数生成了一些 SVG 元素。我想为每个创建的 SVG 元素提供一个下载链接或按钮,以将 SVG 代码保存到用户计算机上的文件中。
我找到了使用 blob 和 URL.createObjectURL 的解决方案,如果我创建一个带有点击处理程序的静态 HTML 页面,它可以正常工作:
<button onclick="download(50)">Download SVG</button>
然而,在 Svelte 中相同的解决方案不会触发下载:
<script>
    const sizes = [20, 50, 90];
    
    function download(id) {
        const svg = document.getElementById(id);
        const blob = new Blob([svg.outerHTML], {type: 'image/svg+xml'});
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `文件名 ${id}.svg`;
        link.click();
        console.log(svg.outerHTML);
        console.log(blob);
        console.log(link);
    }
</script>
{#each sizes as s}
<p>
    <!-- 这个按钮不起作用 -->
    <button on:click={() => download(s)}>Download SVG</button>
    <br>
    <svg id={s} width="200" height="200" xmlns="http://www.w3.org/2000/svg">
        <ellipse cx="100" cy="100" rx={s} ry={s*0.7} fill="orange" stroke="black"/>
    </svg>
</p>
<hr/>
{/each}
英文:
I made a Svelte component, which generates a couple of SVG elements, based on some parameters. I want to provide a download-link or -button for each created SVG element, which saves the SVG code to a file on the user's computer.
I found the solution using blob and URL.createObjectURL suitable. It works if I create a static HTML page with a click handler like so:
<button onclick="download(50)">Download SVG</button>
However the same solution in Svelte does not trigger a download:
<script>
	const sizes = [20, 50, 90];
	
	function download(id) {
		const svg = document.getElementById(id);
		const blob = new Blob([svg.outerHTML], {type: 'image/svg+xml'});
		const link = document.createElement('a');
		link.href = URL.createObjectURL(blob);
		link.download = `File name ${id}.svg`;
		link.click();
		console.log(svg.outerHTML);
		console.log(blob);
		console.log(link);
	}
</script>
{#each sizes as s}
<p>
	<!-- this button does not work -->
	<button on:click={() => download(s)}>Download SVG</button>
	<br>
	<svg id={s} width="200" height="200" xmlns="http://www.w3.org/2000/svg">
		<ellipse cx="100" cy="100" rx={s} ry={s*0.7} fill="orange" stroke="black"/>
	</svg>
</p>
<hr/>
{/each}
答案1
得分: 1
你不能在 REPL 中启动下载,因为它使用 iframe 来隔离输出。这在独立的 Svelte 应用程序中可以正常工作。
英文:
You cannot start downloads in the REPL because it uses an iframe to isolate the output.
This works as expected in a standalone Svelte application.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论