style:
#box{
background-image:url('./img/pone.png')
}
body:
<div id="box">
<p>我想把页面生成图片</p>
<input id="btn" value="保存" onclick="getPhoto()" />
<div>
js:
首先引入:<script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script>
function getPhoto(){
drawCanvas("#box")
}
/* 根据window.devicePixelRatio获取像素比*/
function DPR() {
if (window.devicePixelRatio && window.devicePixelRatio > 1) {
return window.devicePixelRatio;
}
return 1;
}
/* 将传入值转为整数*/
function parseValue(value) {
return parseInt(value, 10);
};
/* 绘制canvas*/
async function drawCanvas(loding) {
// 获取想要转换的 DOM 节点
const dom = document.querySelector(loding);
const box = window.getComputedStyle(dom);
$('#btn').hide();
// DOM 节点计算后宽高
const width = parseValue(box.width);
const height = parseValue(box.height);
// 获取像素比
const scaleBy = DPR();
// 创建自定义 canvas 元素
var canvas = document.createElement('canvas');
// 设定 canvas 元素属性宽高为 DOM 节点宽高 * 像素比
canvas.width = width;
canvas.height = height;
canvas.id = 'can';
// 设定 canvas css宽高为 DOM 节点宽高
canvas.style.width = `${width / 100}rem`;
canvas.style.height = `${height / 100}rem`;
// 获取画笔
const context = canvas.getContext('2d');
// 将所有绘制内容放大像素比倍
// context.scale(scaleBy, scaleBy);
let x = width;
let y = height;
return await html2canvas(dom, {
backgroundColor: null,
canvas,
useCORS: true
}).then(function (canvas) {
let newSrc = convertCanvasToImage(canvas, x, y).src;
return newSrc;
})
}
/*图片转base64格式*/
function convertCanvasToImage(canvas, x, y) {
let image = new Image();
image.setAttribute("crossOrigin", 'Anonymous');
image.width = x;
image.height = y;
image.src = canvas.toDataURL("image/png");
return image;
}