canvas画板
查看演示
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/> </head> <style type="text/css"> body, div{margin:0px;padding:0px;text-align:center} #canvas{ border:2px solid black; border-radius:4px; box-shadow:0px 0px 10px black; -webkit-box-shadow:0px 0px 10px black; -moz-box-shadow:0px 0px 10px black; } #bk{ margin:10px auto; width:400px; height:36px; } .bk{ text-align:center; width:20px; height:20px; margin:12px; display:inline-block; border:1px dotted gray; } .bk.on{border:1px solid red;} </style> <body> <div id="bk"></div> <canvas id="canvas" width="400" height="300"></canvas> </body> <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script> //定义画笔颜色 var bColor = ["#000000", "#999999", "#CC66FF", "#FF0000", "#FF9900", "#FFFF00", "#008000", "#00CCFF"]; //当前画笔颜色 var col = '#FF0000'; function initBrush(){ for(var i = 0; i<bColor.length; i++){ var bk = $('<span class="bk"></span>').css("background-color", bColor[i]).click(function(){ col = $(this).css('background-color'); $(this).addClass('on').siblings().removeClass('on'); }); $('#bk').append(bk); } } function initPainter(){ //绑定绘图canvas var canvas = $('#canvas'), _this = this, x = 0, y = 0; ctx = canvas[0].getContext('2d'); ctx.lineWidth = 2; //绑定鼠标按下时间 canvas.on('mousedown',function(e){ e.preventDefault(); ctx.strokeStyle = col; x = e.offsetX; y = e.offsetY; //开始路径 ctx.beginPath(); ctx.moveTo(x,y); //绑定鼠标移动事件 canvas.on('mousemove',function(e){ var nx = e.offsetX, ny = e.offsetY; ctx.lineTo(x,y); ctx.stroke(); x = nx; y = ny; }) //绑定鼠标抬起事件 canvas.on('mouseup',function(){ //取消鼠标移动事件 canvas.off('mousemove'); }) }) } $(document).ready(function(){ initBrush(); initPainter(); }) </script> </html>