預覽效果:
代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</script>
<script src="http://html2canvas.hertzen.com/dist/html2canvas.js"></script>
<style>
#box {
width: 640px;
height: 640px;
display: inline-block;
position: relative;
border: 1px dashed #ccc;
}
#box img {
width: 100%;
height: 100%;
}
#box canvas {
position: absolute;
bottom: 0;
right: 0;
}
#box2 {
width: 360px;
height: 240px;
display: inline-block;
float: left;
border: 1px dashed #ccc;
}
#box2 canvas {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<p>上傳圖片
<input type="file" id="file-input">
</p>
<div id="box">
</div>
<p>預覽效果 <button onclick="saveImg()">生成圖片</button></p>
<div id="box2"></div>
</body>
</html>
<script>
</script>
<script>
var fileInput = document.querySelector('#file-input');
fileInput.onchange = function (a) {
// 清空上次的圖片
document.getElementById('box').innerHTML = "";
document.getElementById('box2').innerHTML = "";
// 創建圖片
var blob = new Blob(a.target.files)
var img = document.createElement('img');
img.src = URL.createObjectURL(blob);
document.getElementById('box').appendChild(img)
}
</script>
<script>
function saveImg() {
// 生成遮罩
var cvs = document.createElement('canvas');
cvs.width = "640";
cvs.height = "640";
document.getElementById('box').appendChild(cvs);
var g = cvs.getContext("2d");
//繪製圓形
g.arc(100, 100, 600, 0, Math.PI * 2, false);
//圓
var canvasGradient = g.createRadialGradient(100, 100, 600, 100, 100, 200);
canvasGradient.addColorStop(0, "rgba(238,28,37,.1)");
canvasGradient.addColorStop(1, "rgba(238,28,37,.8)");
g.fillStyle = canvasGradient;
g.fill();
//畫五角星
function drawStar(cxt, r, R, x, y, rot, borderWidth, borderStyle, fillStyle) {
cxt.beginPath();
for (var i = 0; i < 5; i++) {
cxt.lineTo((Math.cos((18 + 72 * i - rot) / 180 * Math.PI) * R + x) * 0.5, (-Math.sin((18 + 72 * i - rot) / 180 *
Math.PI) * R + y) * 0.5);
cxt.lineTo((Math.cos((54 + 72 * i - rot) / 180 * Math.PI) * r + x) * 0.5, (-Math.sin((54 + 72 * i - rot) / 180 *
Math.PI) * r + y) * 0.5);
}
cxt.closePath();
cxt.lineWidth = borderWidth;
cxt.strokeStyle = borderStyle;
cxt.fillStyle = fillStyle;
cxt.fill();
cxt.stroke();
}
//左五角星
drawStar(g, 55, 150, 180, 260, 0, 1, '#FFFF00', '#FFFF00')
//右一五角星
drawStar(g, 20, 50, 400, 100, 25, 1, '#FFFF00', '#FFFF00')
//右二五角星
drawStar(g, 20, 50, 500, 200, 45, 1, '#FFFF00', '#FFFF00')
//右三五角星
drawStar(g, 20, 50, 500, 350, 0, 1, '#FFFF00', '#FFFF00')
//右四五角星
drawStar(g, 20, 50, 400, 450, 25, 1, '#FFFF00', '#FFFF00')
// 截圖
html2canvas(document.getElementById("box"), {
useCORS: true
}).then(canvas => {
document.getElementById('box2').appendChild(canvas);
});
}
</script>