canvas写字板功能代码实例
分类:实例代码
分享一段代码实例,它利用canvas实现了写字板功能。
代码实例如下:
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.pipipi.net/" /> <title>前端教程网</title> </head> <body> <canvas id="container" style="background:#666"></canvas> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script> var container = document.getElementById('container'); var context = container.getContext('2d'); var paint = false; //判断是否需要绘画 var mouseX = 0, mouseY = 0, nowX = 0, nowY = 0; //存储坐标记录 var position = { reset: function(actionX, actionY, goalX, goalY) { //坐标替换 paint = true; var order = "" + actionX + "=" + goalX + "," + actionY + "=" + goalY; eval(order); console.log(order); }, init: function() { //坐标清零 console.log("init"); paint = false; mouseX = 0; mouseY = 0; nowX = 0; nowY = 0; } } var canvas = { init: function() { //canvas初始化 context.strokeStyle = "blue"; context.strokeRect(0, 0, 300, 200) }, draw: function(lastX, lastY, nowX, nowY) { //canvas划线 context.strokeStyle = "yellow"; context.lineWidth = 2; context.beginPath(); context.moveTo(lastX, lastY); context.lineTo(nowX, nowY); context.stroke(); position.reset('mouseX', 'mouseY', nowX, nowY); }, redraw: function() { //canvas重绘 position.init(); }, } $('#container').mousedown(function(e) { position.reset('mouseX', 'mouseY', e.pageX - this.offsetLeft, e.pageY - this.offsetTop); console.log(mouseX + ":" + mouseY); }) $('#container').mousemove(function(e) { if (paint) { console.log(mouseX + ":" + mouseY); position.reset('nowX', 'nowY', e.pageX - this.offsetLeft, e.pageY - this.offsetTop); canvas.draw(mouseX, mouseY, nowX, nowY); } }) $("#container").mouseup(function(e) { if (paint) { position.init(); // canvas.returnData(); } }) $("#container").mouseleave(function(e) { if (paint) { position.init(); } }) </script> </body> </html>
canvas写字板功能代码实例,这样的场景在实际项目中还是用的比较多的,关于canvas写字板功能代码实例就介绍到这了。
canvas写字板功能代码实例属于前端实例代码,有关更多实例代码大家可以查看。