canvas绘画板的实现(兼容手机)
canvas绘画板的实现(兼容手机)
新项目有一个需求:客户需要在订单确认的时候签名。
第一反应就是用html的canvas实现,同事一起商量了下,canvas有三个制约:
- canvas必须要用鼠标,签名会很难看;
- 手机端web app怎么实现签名?
- 签名好的canvas怎么作为图片提交到服务器?
纠结了一天,研究了下canvas,终于有了点眉目。先看看实际效果
手机端的不好截图,下面有源码可以下载。下面是源码截图(懒到一定程度了,截图吧^_^),代码都有注释,我相信读者花点时间肯定能看明白。
下面是app.js源码(太长了,不能截图了。。~~~~(>_<)~~~~)
//动态设置canvas的大小 function resizeCanvas() { $('#drawer').attr("width", $('.panel-body').width()); if(!$('.panel-body').height()){ $('#drawer').attr("height", $('.panel-body').height()); }else{ $('#drawer').attr("height", 300); } }; var canvas,board; canvas = document.getElementById('drawer'); board = canvas.getContext('2d'); var mousePress = false; var last = null; //开始绘制 function beginDraw(){ mousePress = true; } //绘制 function drawing(event){ event.preventDefault(); if(!mousePress)return; var xy = pos(event); if(last!=null){ board.beginPath(); board.moveTo(last.x,last.y); board.lineTo(xy.x,xy.y); board.stroke(); } last = xy; } //结束绘制 function endDraw(event){ mousePress = false; event.preventDefault(); last = null; } //获取位置 function pos(event){ var x,y; if(isTouch(event)){ x = event.touches[0].pageX-event.target.offsetLeft; y = event.touches[0].pageY-event.target.offsetTop; }else{ x = event.offsetX; y = event.offsetY; } return {x:x,y:y}; } //检测是touch还是mouse事件 function isTouch(event){ var type = event.type; if(type.indexOf('touch')>=0){ return true; }else{ return false; } } //清除轨迹 function clearArea() { board.setTransform(1, 0, 0, 1, 0, 0); board.clearRect(0, 0, board.canvas.width, board.canvas.height); } //转换成图片显示 function convertCanvasToImage() { var image = canvas.toDataURL("image/png"); $('#image').html("<img src='"+image+"' alt='from canvas'/>"); } //生成图片并上传到服务器 function UploadPic() { var Pic = canvas.toDataURL("image/png"); Pic = Pic.replace(/^data:image\/(png|jpg);base64,/, "") $.ajax({ type: 'POST', url: 'url', data: '{ "imageData" : "' + Pic + '" }', contentType: 'application/json; charset=utf-8', dataType: 'json', success: function (msg) { console.log("图片上传成功"); }, error: function(msg) { alert("需要服务器资源"); } }); } board.lineWidth = 2; board.strokeStyle="#000"; board.lineJoin = "round"; canvas.onmousedown = beginDraw; canvas.onmousemove = drawing; canvas.onmouseup = endDraw; canvas.addEventListener('touchstart',beginDraw,false); canvas.addEventListener('touchmove',drawing,false); canvas.addEventListener('touchend',endDraw,false);
ok,结束,下班~~
源码地址:canvas.rar
相关推荐
大地飞鸿 2020-11-12
星星有所不知 2020-10-12
jinxiutong 2020-07-26
MIKUScallion 2020-07-05
songfens 2020-07-05
songfens 2020-06-11
songfens 2020-06-08
northwindx 2020-05-31
northwindx 2020-05-31
northwindx 2020-05-27
northwindx 2020-05-25
MIKUScallion 2020-05-25
jinxiutong 2020-05-10
xdyangxiaoromg 2020-05-10
大地飞鸿 2020-05-06
northwindx 2020-04-25