效果:
直接运行代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=no"/>
<title></title>
<style type="text/css">
html,
body {
width: 100%;
height: 100%;
}
* {
margin: 0;
padding: 0;
}
#canvas {
position: relative;
width: 100%;
height: 100%;
}
#canvas canvas {
display: block;
}
#clearCanvas,
#saveCanvas {
position: absolute;
bottom: 0;
z-index: 1;
width: 50%;
height: 6vh;
border: 1px solid #dedede;
line-height: 6vh;
text-align: center;
font-size: 2vh;
}
#clearCanvas {
left: 0;
}
#saveCanvas {
right: 0;
}
.errorCanvas {
width: 100%;
height: 100%;
text-align: center;
transform: translateY(40%);
}
</style>
</head>
<body>
<div id="canvas">
<p id="clearCanvas">清除</p>
<p id="saveCanvas">保存</p>
</div>
<script type="text/javascript">
window.onload = function () {
new lineCanvas({
el: document.querySelector('#canvas'),
clearEl: document.querySelector('#clearCanvas'),
saveEl: document.querySelector('#saveCanvas'),
lineWidth: 4,
color: '#333',
background: '#FFF'
});
}
function lineCanvas(obj) {
this.lineWidth = 5;
this.color = '#000';
this.background = '#fff';
for (var i in obj) {
this[i] = obj[i];
};
this.canvas = document.createElement('canvas');
if (!(this.canvas.getContext && this.canvas.getContext('2d'))) {
this.section = document.createElement('section');
this.section.className = 'errorCanvas';
this.section.innerHTML = '对不起,当前浏览器暂不支持此功能!'
this.el.prepend(this.section);
return
}
this.canvas.width = this.el.clientWidth;
this.canvas.height = this.el.clientHeight;
this.el.prepend(this.canvas);
this.cxt = this.canvas.getContext('2d');
this.cxt.fillStyle = this.background;
this.cxt.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.cxt.strokeStyle = this.color;
this.cxt.lineWidth = this.lineWidth;
this.cxt.lineCap = 'round'; // 线条末端添加圆形线帽,减少线条的生硬感
this.cxt.lineJoin = 'round'; // 线条交汇时为原型边角
// 利用阴影,消除锯齿
this.cxt.shadowBlur = 1;
this.cxt.shadowColor = '#000';
// 开始绘制
this.canvas.addEventListener('touchstart', function (e) {
this.cxt.beginPath();
this.cxt.moveTo(e.changedTouches[0].pageX, e.changedTouches[0].pageY);
}.bind(this), false);
// 绘制中
this.canvas.addEventListener('touchmove', function (e) {
this.cxt.lineTo(e.changedTouches[0].pageX, e.changedTouches[0].pageY);
this.cxt.stroke();
}.bind(this), false);
// 结束绘制
this.canvas.addEventListener('touchend', function (e) {
this.cxt.closePath();
}.bind(this), false);
// 清除画布
this.clearEl.addEventListener('click', function () {
this.cxt.clearRect(0, 0, this.canvas.width, this.canvas.height);
}.bind(this), false);
// 保存图片
this.saveEl.addEventListener('click', function () {
var imgBase64 = this.canvas.toDataURL();
var imgPng = this.canvas.toDataURL('image/png');
var imgJpg = this.canvas.toDataURL('image/jpeg', 0.8);
console.log(imgPng, imgJpg);
}.bind(this), false);
}
</script>
</body>
</html>