HTML5 Canvas实例画板

首先,我们需要知道如何用canvas画线条

其次,画线条的时机,什么开始画,什么时候结束画。

1)生成静态的线条

<body>
  <canvas id="plain" width="500" height="300">
  该浏览器不支持此格式
  </canvas>
 <script type="text/javascript">
 var c=document.getElementById("plain");
 var plain=c.getContext("2d");
 plain.beginPath();
 plain.moveTo(10,10);//起始点
 plain.lineTo(200,150);//终止点
 plain.stroke();
 </script>
 </body>
如下所示:

2)我们希望在鼠标左击放开时,会生成一个点,如果不放,移动时会根据移动的方向,生成线条;

我们需要知道的鼠标事件,我们这里使用的是jquery,jquery放在创建网页的文件夹下。

mousedown 鼠标按下运行脚本

mousemove 鼠标移动运行脚本

mouseup 鼠标松开运行脚本

<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>Document</title>
  <script src="jquery-1.11.1.js"></script>
  <style type="text/css">
#plain{border:1px solid #ccc;}
  </style>
 </head>
 <body>
  <canvas id="plain" width="500" height="300">
  该浏览器不支持此格式
  </canvas><br>
 
 <input id="changeColor" type="color">
 <input id="changeWidth" type="number">
 <input id="clear" type="submit" value="clear">
 </body>
 <script type="text/javascript">
 var c=document.getElementById("plain");
 var plain=c.getContext("2d");
 var x;
 var y;
 var mousedownflag=false;
  plain.strokeStyle="blue";
  plain.lineWidth="5";
 $("#plain").mousedown(function(e){
  plain.beginPath();
  plain.strokeStyle=$("#changeColor").val();
  plain.lineWidth=$("#changeWidth").val();
  x=e.clientX-this.offsetLeft;
  y=e.clientY-this.offsetTop;
  plain.moveTo(x,y);
  mousedownflag=true;
 });
 $("#plain").mousemove(function(e){
  x=e.clientX-this.offsetLeft;
  y=e.clientY-this.offsetTop;
  if(mousedownflag)
	 {
       plain.lineTo(x,y);
       plain.stroke();
	 }
 });
 $("#plain").mouseup(function(){
  mousedownflag=false;
 });
 $("#changeColor").change(function()
 {
     color=$(this).val();
 });
 $("#changeWidth").change(function(){
	 if($(this).val()<1)
	 {
	   $(this).val(1);
	 }
     width=$(this).val();
 });
 $("#clear").click(function(){
  plain.clearRect(0,0,500,300);
 });
 </script>
</html>

运行结果如下所示:






  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值