JSFiddle - React, Tailwind, and code Playground
by mizobata
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<button id="open-btn">ダウンロード画面へ</button>
<ul id="tab-menu">
<li>Content1</li>
<li>Content2</li>
</ul>
<div id="tab-content1">
<h1>Content1 Sample Text</h1>
sample sample sample<br>
sample sample sample
</div>
<div id="tab-content2">
<h1>Content2 Sample Text</h1>
sample sample sample<br>
sample sample sample
</div>
CSS
h1 {
font-size: 25px;
}
JavaScript
const openBtn = document.getElementById('open-btn');
openBtn.addEventListener('click', handleClickOpen);
function handleClickOpen(e) {
const newWindow = window.open();
// ダウンロード用のボタン生成
const button = document.createElement('button');
button.innerText = 'ダウンロード';
// ラッパー用Div
const wrapper = document.createElement('div');
wrapper.setAttribute('id', 'wrapper');
// 欲しいDOMを抜き出す
const ids = ['tab-menu', 'tab-content1', 'tab-content2'];
ids.forEach(id => {
const elm = document.getElementById(id); // 指定要素を取得
wrapper.appendChild(elm.cloneNode(true)); // クローンした要素を追加
});
// 子ウィンドウのbodyに追加
newWindow.document.body.appendChild(button);
newWindow.document.body.appendChild(wrapper);
// ボタンをクリックしたら、ダウンロードする
button.addEventListener('click', e => {
html2canvas(newWindow.document.getElementById('wrapper'), {
onrendered: canvas => {
canvas.toBlob(blob => {
const a = document.createElement('a');
a.download = 'wrapper.png';
a.target = '_blank';
a.href = window.URL.createObjectURL(blob);
a.click();
newWindow.close();
});
}
});
});
}