<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>cavans 鼠标画线</title> <style> #canvas{ background: orange; } </style> </head> <body> <canvas id="canvas" width="800px" height="400px"></canvas> <script> //根据鼠标的坐标来画线 var obj = document.getElementById('canvas'); var oCanvas = obj.getContext('2d'); obj.onmousedown = function(ev){ var ev = ev || window.event; //选用白色笔触 oCanvas.strokeStyle = '#fff'; //起始位置 oCanvas.moveTo(ev.clientX - obj.offsetLeft , ev.clientY - obj.offsetTop); document.onmousemove = function(ev){ var ev = ev || window.event; //移动位置 oCanvas.lineTo(ev.clientX - obj.offsetLeft , ev.clientY - obj.offsetTop); oCanvas.stroke(); } document.onmouseup = function(){ document.onmousemove = null; document.onmouseup = null; } } </script> </body> </html>