canvas画板是模拟鼠标在canvas画布上移动写字效果 通过获取鼠标的坐标值, 在通过canvas画布的画笔进行连接
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
<script src="jquery_1_12_4.js"></script>
</head>
<body>
<canvas width="100%" height="100%"></canvas>
<script>
$(function(){
var isDown = false;
var canvas = $('canvas').get(0);
canvas.height = $(window).height();
canvas.width = $(window).width();
var ctx = canvas.getContext('2d');
ctx.strokeStyle = 'black';
ctx.beginPath();
$('body').mousedown(function(e){
isDown = true;
ctx.moveTo(e.clientX,e.clientY);
}).mousemove(function(e){
if(isDown){
ctx.lineTo(e.clientX,e.clientY);
}
ctx.stroke();
}).mouseup(function(){
isDown = false;
})
})
</script>
</body>
</html>分析
var isDown = false; 默认鼠标松开
在默认情况下,鼠标为松开,当用户触发鼠标mousedown事件时
变量isDown变成true
并在画布上记录用户鼠标按下的位置的点
$('body').mousedown(function(e){
isDown = true;
ctx.moveTo(e.clientX,e.clientY);
})为了实现只有鼠标按下时,并且拖动才能绘制图片,用户触发了鼠标事件
mousemove后,isDwon的状态必须为true才能绘制图
if(isDown){
ctx.lineTo(e.clientX,e.clientY);
}
ctx.stroke();最后,当用户松开鼠标时,isDwon状态恢复到初始状态 isDwon = false;
效果图
这下真的有点皮了哈

来个gif图片吧

随时随地看视频