<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<canvas id="canvas" width="490" height="220"></canvas>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array(); //存储路径点
var paint; //是否绘制,mousedown时置为true
function addClick(x, y, dragging) {
clickX.push(x);
clickY.push(y);
clickDrag.push(dragging);
}
function redraw() {
context = document.getElementById('canvas').getContext("2d");
context.clearRect(0, 0, context.canvas.width, context.canvas.height); // 清除画布内容
context.strokeStyle = "#df4b26"; //设置线条颜色
context.lineJoin = "round"; //当两条线条交汇时,创建圆形边角
context.lineWidth = 5; //线条粗细
for(var i = 0; i < clickX.length; i++) {
context.beginPath(); //开始一条路径,或重置当前的路径
if(clickDrag[i] && i) {
context.moveTo(clickX[i - 1], clickY[i - 1]);
} else {
context.moveTo(clickX[i] - 1, clickY[i]);
}
context.lineTo(clickX[i], clickY[i]);
context.closePath();
context.stroke(); //绘制路径
}
}
$('#canvas').mousedown(function(e) {
//console.log("鼠标点击");
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
paint = true;
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
redraw();
});
$('#canvas').mousemove(function(e) {
//console.log(e.pageX + ":" + e.pageY);
if(paint) {
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
redraw();
}
});
$('#canvas').mouseup(function(e) {
paint = false;
});
$('#canvas').mouseleave(function(e) {
paint = false;
});
</script>
</body>
</html>