<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container {
color: red;
}
/* body>img{
display:none!important;
} */
</style>
</head>
<body>
<div class="container" >
<button onclick="convertHtml2Canvas()">截取</button>
<button onclick="saveImage()">保存</button>
<div id="capture" style="padding: 10px; background: #f5da55">
<h4 style="color: #000; ">Hello world!</h4>
</div>
<a herf="" id="aCanvas" download="截图.png" style="display:none;" target="_blank"></a>
<div id="divCanvas" style="padding: 0px;height: 200px;">
</div>
</div>
<link rel="stylesheet" href="jquery.Jcrop.css">
<script src="./jquery-1.8.0.min.js"></script>
<script src="./html2canvas.js"></script>
<script src="jquery.Jcrop.js"></script>
<script>
var jcropApi;
var x1,y1,w,h;
//先将目标区域生成一张图片,然后将这个图片放入编辑区域divCanvas中,再对图片生成选区
function convertHtml2Canvas() {
html2canvas(document.getElementById("capture"), {
allowTaint: false,
taintTest: true
}).then(function(canvas) {
var img = convertCanvasToImage(canvas);
img.id="imgCanvas";
$("#divCanvas").html(img);
$('#imgCanvas').Jcrop({
onChange: jcropChange,
allowSelect: true,
baseClass: 'jcrop'
}, function() {
jcropApi = this;
});
}).catch(function(e) {
console.error('error', e);
});
}
//画选区
function jcropChange(c){
x1=c.x;
y1=c.y;
w=c.w;
h=c.h;
}
//保存选区内容
function saveImage(){
var image = document.getElementById("imgCanvas");
var canvas = convertImageToCanvas(image,x1,y1,w,h);
var a = document.getElementById("aCanvas");
a.setAttribute("href", canvas.toDataURL("image/png"));
a.click();
}
// Converts canvas to an image
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png", 0.1);
return image;
}
// Converts image to canvas; returns new canvas element
function convertImageToCanvas(image, startX, startY, width, height) {
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
canvas.getContext("2d").drawImage(image, startX, startY, width, height, 0, 0, width, height);
return canvas;
}
</script>
</body>
</html>