引:https://zhoushuo.me/drawingborad/
1. 主要实现能够提供给用户绘图的功能;
实现:通过点击,移动事件获取当前坐标,并且在移动的时候将当前的坐标作为下一次起始值的坐标,然后调用绘图功能;
根据四个坐标点绘图。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas画板</title>
<style type="text/css">
#myCanvas {
border: 1px solid #ccc;
}
.canvasBox {
width: 600px;
margin: 0 auto;
text-align: center;
}
</style>
</head>
<body>
<div class="canvasBox">
<canvas id="myCanvas" height="400" width="500"></canvas>
</div>
<script type="text/javascript">
var canvas = document.getElementById('myCanvas');
var ctx = myCanvas.getContext('2d');
let clear = false;
let lWidth = 4;
listenToUser(canvas);
function listenToUser(canvas) {
let painting = false;
let lastPoint = {x: undefined, y: undefined};
if (document.body.ontouchstart !== undefined) {
canvas.ontouchstart = function (e) {
console.log(e)
var canvasLeft = e.target.offsetLeft;
var canvasTop = e.target.offsetTop;
painting = true;
let x = e.changedTouches[0].clientX-canvasLeft;
let y = e.changedTouches[0].clientY-canvasTop;
lastPoint = {"x": x, "y": y};
ctx.save();
};
canvas.ontouchmove = function (e) {
if (painting) {
var canvasLeft = e.target.offsetLeft;
var canvasTop = e.target.offsetTop;
let x = e.changedTouches[0].clientX-canvasLeft;
let y = e.changedTouches[0].clientY-canvasTop;
let newPoint = {"x": x, "y": y};
drawLine(lastPoint.x, lastPoint.y, newPoint.x, newPoint.y);
lastPoint = newPoint;
}
};
canvas.ontouchend = function () {
painting = false;
}
} else {
canvas.onmousedown = function (e) {
var canvasLeft = e.target.offsetLeft;
var canvasTop = e.target.offsetTop;
painting = true;
let x = e.clientX-canvasLeft;
let y = e.clientY-canvasTop;
lastPoint = {"x": x, "y": y};
ctx.save();
};
canvas.onmousemove = function (e) {
if (painting) {
var canvasLeft = e.target.offsetLeft;
var canvasTop = e.target.offsetTop;
let x = e.clientX-canvasLeft;
let y = e.clientY-canvasTop;
let newPoint = {"x": x, "y": y};
drawLine(lastPoint.x, lastPoint.y, newPoint.x, newPoint.y,clear);
lastPoint = newPoint;
}
};
canvas.onmouseup = function () {
painting = false;
};
canvas.mouseleave = function () {
painting = false;
}
}
}
function drawLine(x1, y1, x2, y2) {
ctx.lineWidth = lWidth;
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
ctx.closePath();
}
</script>
</body>
</html>