效果图:
canvas_2.gif
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
canvas {
display: block;
background: #dbdbdb;
color: #1aa196;
}
.clear{
position: fixed;
top: 20px;
right: 20px;
color: coral;
font-weight: bold;
font-size: 20px;
text-decoration: underline;
cursor: pointer;
}
</style>
</head>
<body>
<span class="clear" onclick="clearCanvas()">清空画布</span>
<canvas id="canvas"></canvas>
</body>
<script>
let w = window.innerWidth;
let h = window.innerHeight;
let canvas = document.getElementById("canvas");
canvas.width = w;
canvas.height = h;
let ctx = canvas.getContext("2d");
let start_x, start_y; //每次绘制直线的起始点
let lineArray = []; //储存绘制的直线数组
//清空画布方法
function clearCanvas() {
ctx.clearRect(0, 0, w, h);
lineArray = []
}
document.addEventListener("mousedown", mouse_down)
document.addEventListener("mouseup", mouse_up)
//鼠标按下方法
function mouse_down(e) {
start_x = e.clientX;
start_y = e.clientY;
console.log(e.clientX, e.clientY)
console.log("鼠标按下")
document.addEventListener("mousemove", mouse_move)
}
//鼠标移动方法
function mouse_move(e) {
//在鼠标移动绘制直线时,都要清除下画布,否则会有很多移动痕迹
ctx.clearRect(0, 0, w, h);
//此处是为绘制多条直线时,通过遍历之前绘制的直线,进而实现绘制多条直线的效果
for (let i = 0; i < lineArray.length; i++) {
draw_line(lineArray[i].startX, lineArray[i].startY, lineArray[i].endX, lineArray[i].endY)
}
draw_line(start_x, start_y, e.clientX, e.clientY)
}
//鼠标松开方法
function mouse_up(e) {
console.log(e.clientX, e.clientY)
console.log("鼠标松开")
//每次鼠标松开的时候,都会创建一个直线对象的相关属性,储存到 lineArray 里面
lineArray.push(new draw_line(start_x, start_y, e.clientX, e.clientY))
console.log(lineArray)
//移除鼠标监听
document.removeEventListener("mousemove", mouse_move)
}
//绘制线条的样式
function draw_line(start_x, start_y, end_x, end_y) {
this.startX = start_x;
this.startY = start_y;
this.endX = end_x;
this.endY = end_y;
ctx.beginPath();
// 定义边框颜色
ctx.strokeStyle = 'black'
// 定义边框宽度
ctx.lineWidth = 2;
ctx.moveTo(start_x, start_y);
ctx.lineTo(end_x, end_y);
ctx.stroke();
ctx.closePath();
}
</script>
</html>
网友评论