canvas简单画图板
<!DOCTYPE html> <html lang='en'> <head> <meta charset='UTF-8'> <title>Title</title> </head> <body> <canvas id='cas' style="border:1px solid red" width='600' height='400'></canvas> <div> <input type="button" value="蓝色" onclick="blue()"/> <input type="button" value="绿色" onclick="green()"/> <input type="button" value="粉色" onclick="pink()"/> <select name="" id="" onchange="change(this)"> <option value="1">1px</option> <option value="4">4px</option> <option value="8">8px</option> <option value="20">20px</option> </select> <input type="button" value="清空画布" onclick="clearCas()"> </div> <script> //手写输入!! var cas = document.getElementById( 'cas' ); var context = cas.getContext( '2d' ); var mouseDown = false;//定义一个参数判断鼠标是否按下 var points = [];//定义一个数组存放鼠标不停移动时的坐标 // 添加鼠标移动事件 cas.addEventListener( 'mousemove', function ( e ) {//鼠标移动事件 // 注册按下与抬起的事件 cas.addEventListener( 'mousedown',function () {//鼠标按下事件 mouseDown = true; }); cas.addEventListener( 'mouseup',function () {//鼠标抬起事件 mouseDown = false; }); if ( mouseDown ) { points.push( { x: e.offsetX, y: e.offsetY } ); // 不断的刷新, 绘制 context.beginPath();//开启新的绘制 // 绘图 context.moveTo( points[ 0 ].x, points[ 0 ].y );//起始位置 // 循环 lineTo for ( var i = 1; i < points.length; i++ ) { context.lineTo( points[ i ].x, points[ i ].y ); } context.stroke();//描边 } else { points = []; } }); /*选择画笔颜色 */ function blue(){ context.strokeStyle="blue";//画笔颜色改为蓝色 } function green(){ context.strokeStyle="green"; } function pink(){ context.strokeStyle='pink'; } /*选择画笔粗细*/ function change(dom){ context.lineWidth=dom.value-0; } /*清空画布*/ function clearCas(){ context.clearRect(0,0,cas.width,cas.height); } </script> </body> </html>