1.HTML及css样式
<canvas id="myCanvas">
您的浏览器不支持canvas,请升级!
</canvas>
<style>
canvas{
display: block;
margin: 20px auto;
background: gray;
}
</style>
2.js代码
<script>
(function(){
// 获取canvas元素
var canvasNode = document.querySelector("#myCanvas");
// 设置画布宽高
canvasNode.width = 800;
canvasNode.height = 600;
// 获取绘图上下文
var ctx = canvasNode.getContext('2d');
ctx.lineWidth = 2;
//绑定鼠标按下事件
canvasNode.onmousedown = function(event) {
// 开启路径
ctx.beginPath();
// 设置起始点
ctx.moveTo(event.offsetX,event.offsetY);
// 绑定鼠标移动事件
document.onmousemove = function(event) {
// 设置连接点
ctx.lineTo(event.clientX - canvasNode.offsetLeft,event.clientY - canvasNode.offsetTop);
ctx.stroke(); //描边
}
document.onmouseup = function() {
this.onmousemove = null;
}
}
})();
3.效果图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZbmxR9bM-1596508551264)(https://s1.ax1x.com/2020/08/04/awrlwQ.png)]