<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
html, body, div {
padding: 0;
margin: 0;
}
html, body {
height: 100%;
}
div {
width: 50%;
height: 30%;
background: #61B3E6;
}
</style>
</head>
<body>
<div class="container"></div>
<script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script>
<script>
/**
* 根据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 (selector) {
// 获取想要转换的 DOM 节点
const dom = document.querySelector(selector);
const box = window.getComputedStyle(dom);
// 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 * scaleBy;
canvas.height = height * scaleBy;
// 设定 canvas css宽高为 DOM 节点宽高
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
// 获取画笔
const context = canvas.getContext('2d');
// 将所有绘制内容放大像素比倍
context.scale(scaleBy, scaleBy);
let x = width;
let y = height;
return await html2canvas(dom, {canvas}).then(function () {
convertCanvasToImage(canvas, x ,y)
})
}
/**
* 图片转base64格式
*/
function convertCanvasToImage(canvas, x, y) {
let image = new Image();
// let _container = document.getElementsByClassName('container')[0];
// let _body = document.getElementsByTagName('body')[0];
image.width = x;
image.height = y;
image.src = canvas.toDataURL("image/png");
// _body.removeChild(_container);
document.body.appendChild(image);
return image;
}
drawCanvas('.container')
</script>
</body>
</html>