一个基本的演示(可能需要 tweeking):http://jsfiddle.net/m1erickson/H7vRw/
您可以请求浏览器将鼠标事件(mousedown、mouseup、mousemove)发送到处理这些事件的函数。
// add an html canvas element
<canvas id="canvas" width=300 height=200></canvas>
// ask the browser to send mouse events to handler functions
// for example, mousedown events will be sent to the handleMouseDown function
// this example uses jQuery for browser compatibility
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseUp(e);});
在 mousedown 处理程序中:
- 获取鼠标位置。
- 设置一个标志,指示拖动已开始
- 保存鼠标位置(它将是行的起点)
鼠标按下代码:
function handleMouseDown(e){
// let the browser know we will handle this event
e.preventDefault();
// get the mouse position
var mouseX=parseInt(e.clientX-offsetX);
var mouseY=parseInt(e.clientY-offsetY);
// set an isDown flag to indicate dragging has started
isDown=true;
// save the starting mouse position
// (it will be the beginning point of the line);
startX=mouseX;
startY=mouseY;
}
在 mousemove 处理程序代码中:
- 获取鼠标位置
- 清除画布并从保存的起始位置画一条线到此鼠标位置
鼠标移动代码:
function handleMouseMove(e){
// if we're not dragging, ignore this mousemove
if(!isDown){ return; }
// let the browser know we will handle this event
e.preventDefault();
// get the mouse position
var mouseX=parseInt(e.clientX-offsetX);
var mouseY=parseInt(e.clientY-offsetY);
// draw the current line
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.moveTo(startX,startY);
ctx.lineTo(mouseX,mouseY);
ctx.stroke()
}
在 mouseup 处理程序中:
鼠标代码:
function handleMouseUp(e){
// let the browser know we will handle this event
e.preventDefault();
// clear the dragging flag since the drag is donw
isDown=false;
}