效果图:
canvas_02.gif下面这张图应该可以解决你的部分疑惑,想深入了解的话可以 点击了解更多,或者 点击测试 ~~~~
image.png
代码如下:
<!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;
}
.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");
let ctx = canvas.getContext("2d");
canvas.width = w;
canvas.height = h;
document.addEventListener("mousedown", mouse_down)
document.addEventListener("mouseup", mouse_up)
//清空画布方法
function clearCanvas() {
ctx.clearRect(0, 0, w, h);
}
//鼠标点击时
function mouse_down(e) {
let start_x = e.clientX
let start_y = e.clientY
console.log(start_x, start_y)
ctx.beginPath();
// 定义线的粗细
ctx.lineWidth = 5;
// 定义线的颜色
ctx.strokeStyle = 'black'
ctx.moveTo(start_x, start_y);
document.addEventListener("mousemove", mouse_move)
}
//鼠标移动时
function mouse_move(e) {
let move_x = e.clientX
let move_y = e.clientY
console.log(move_x, move_y)
ctx.lineTo(move_x, move_y);
ctx.stroke();
}
////鼠标松开时
function mouse_up(e) {
//移除鼠标监听
document.removeEventListener("mousemove", mouse_move)
}
</script>
</html>
网友评论