为了账号安全,请及时绑定邮箱和手机立即绑定

canvas简单画板

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;


效果图

这下真的有点皮了哈


5b8774f100013ec206000320.jpg


来个gif图片吧


5b8774f10001c15406000286.jpg


点击查看更多内容
1人点赞

若觉得本文不错,就分享一下吧!

0 评论

作者其他优质文章

正在加载中
Web前端工程师
手记
粉丝
23
获赞与收藏
130

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

举报

0/150
提交
取消