Canvas实现鼠标在网页上涂画

来源:互联网 发布:linux下perl开发工具 编辑:程序博客网 时间:2024/06/05 02:02

使用Canvas实现,鼠标在网页上进行涂抹绘画。
效果如下:

这里写图片描述

主要是使用了canvas绘图,图画的轨迹是利用一张黑色圆点图片重复绘制叠加而成,具备点击浏览器前进后退按钮的实现返回前一笔画或后一笔画的功能。
注意,因为这里用到了getImageData()方法,所以需要在Web服务器中打开。
代码如下:

<!DOCTYPE html><html><head>  <meta charset="utf-8">  <meta name="viewport" content="width=device-width">  <title>Canvas Write</title>  <style>    #canvas{      position:absolute;      top:0;      left:0;      width:100%;      height:100%;      margin:0;    }    #image{      // 把需要用来绘制轨迹的黑色圆点图片隐藏起来      display: none;    }  </style></head><body>  <canvas id='canvas' width='400' height='300'></canvas>  <img id='image' width='6' width='6' src="1.png" alt=""></body></html><script>  var image=document.getElementById('image');  var canvas=document.getElementById('canvas');  var context=canvas.getContext('2d');  var isDrawing=false;  var state=context.getImageData(0,0,canvas.width,canvas.height);  // 网页刚初始化后,将初始状态的网页状态存到浏览器缓存中  history.pushState(state,null);  canvas.addEventListener('mousedown',startDrawing,false);  canvas.addEventListener('mousemove',draw,false);  canvas.addEventListener('mouseup',stopDrawing,false);  function startDrawing() {    // 使用此参数来规范鼠标行为,只有鼠标左键按下才能绘制轨迹    isDrawing=true;  }  function draw() {    if(isDrawing){        var sx=canvas.width/canvas.offsetWidth;        var sy=canvas.height/canvas.offsetHeight;        var x=sx*event.clientX-image.offsetWidth/2;        var y=sy*event.clientY-image.offsetHeight/2;        // 根据黑色圆点小图片重复多次绘制轨迹        context.drawImage(image,x,y)      }  }  function stopDrawing() {    isDrawing=false;    var state=context.getImageData(0,0,canvas.width,canvas.height);    // 鼠标左键弹起,表明当前轨迹结束,保存当前状态,以便于浏览器历史记录    history.pushState(state,null)  }  window.onpopstate =function loadState(e) {    // 浏览器后退功能,首先擦除当前画布上所有内容    context.clearRect(0,0,canvas.width,canvas.height);    // 然后将前一个状态绘制到网页上    if(e.state){      context.putImageData(e.state,0,0);    }  }</script>
0 0
原创粉丝点击