文章目录
- 准备
- html
- JavaScript
准备
NPM下载指令
npm install dom-to-image
框架加载
/* in ES 6 */ import domtoimage from 'dom-to-image';
/* in ES 5 */ var domtoimage = require('dom-to-image');
CDN(标签)加载
案例
<script src="dist/dom-to-image.min.js"></script>
引入方式
src/dom-to-image.js
或
dist/dom-to-image.min.js
”
方法返回domtoimage
对象,对象中存有对应方法。
详细文档传送门
html
<!-- 需要下载的元素标签 -->
<div id="idDemo" class="w_200 h_200 d_f jc_c ai_c p_r bc_1296db"><div id="idItem" class="p_a fs_26 color_fff fw_800">1</div><div id="idItem" class="p_a fs_26 color_fff fw_800">5</div><div id="idItem" class="p_a fs_26 color_fff fw_800">2</div><div id="idItem" class="p_a fs_26 color_fff fw_800">8</div><div id="idItem" class="p_a fs_26 color_fff fw_800">9</div><div id="idItem" class="p_a fs_26 color_fff fw_800">6</div><div id="idItem" class="p_a fs_26 color_fff fw_800">8</div><div id="idItem" class="p_a fs_26 color_fff fw_800">2</div><div id="idItem" class="p_a fs_26 color_fff fw_800">5</div><div id="idItem" class="p_a fs_26 color_fff fw_800">1</div><div id="idItem" class="p_a fs_26 color_fff fw_800">7</div>
</div><!-- 下载操作 -->
<div class="m_t_68 bc_1296db radius_6 ta_c p_10 color_fff cursor_pointer" onclick="domToImg()">创建并下载图片</div>
JavaScript
/*** 实现环形文字*/
function init() {let elItem = document.querySelectorAll('#idItem'),radius = document.querySelector('#idDemo').clientWidth / 3.2,itemLen = elItem.length,pieceDeg = 360 / itemLen;for (let i = 0; i < itemLen; i++) {let t = i * pieceDeg,x = undefined,y = undefined,deg = t;t = (Math.PI / 180) * t;x = Math.sin(t) * radius;y = -Math.cos(t) * radius;elItem[i].style.transform = `translate(${x}px, ${y}px) rotate(${deg}deg) scale(2, 1)`;}
}
init();/*** 创建并下载图片*/
async function domToImg() {let idDemo = document.querySelector('#idDemo'),dataUrl = await domtoimage.toPng(idDemo, 1),a = document.createElement("a"),filename = document.title,event = new MouseEvent("click");a.download = filename;a.href = dataUrl;a.dispatchEvent(event);
}