<!DOCTYPE html>
<html>
<head>
<style>
canvas {
border: 1px dashed black;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
</head>
<body>
<canvas id="canvas" width="490" height="220"></canvas>
<div style="margin-left:100px; margin-top: 200px; width:200px; height:100px; border:1px solid red; position:relative;">
<div id="inner" style="width: 10px; height:10px; background-color: green; position: relative; left: 10px; "></div>
</div>
<script>
context = document.getElementById('canvas').getContext("2d");
$('#canvas').mousedown(function(e){
console.log(e);
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
paint = true;
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
redraw();
});
$('#canvas').mousemove(function(e){
if(paint){
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
redraw();
}
});
$('#canvas').mouseup(function(e){
paint = false;
});
$('#canvas').mouseleave(function(e){
paint = false;
});
var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array();
var paint;
function addClick(x, y, dragging)
{
clickX.push(x);
clickY.push(y);
clickDrag.push(dragging);
}
function redraw(){
context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears the canvas
context.strokeStyle = "#df4b26";
context.lineJoin = "round";
context.lineWidth = 5;
for(var i=0; i < clickX.length; i++) {
context.beginPath();
if(clickDrag[i] && i){
context.moveTo(clickX[i-1], clickY[i-1]);
}else{
context.moveTo(clickX[i]-1, clickY[i]);
}
context.lineTo(clickX[i], clickY[i]);
context.closePath();
context.stroke();
}
}
</script>
</body>
</html>
----------------------------------------------------------------------------------------------
PageX和clientX 的区别
pageX指鼠标在页面上的位置,以页面左侧为参考点
clientX指可视区域内离左侧的距离,以滚动条滚动到的位置为参考点。各个浏览器相同。
即当有滚动条时clientX 小于 pageX
clientX 鼠标相对于浏览器窗口可视区域的X,Y坐标(窗口坐标),可视区域不包括工具栏和滚动条
pageX 它们使用的是文档坐标而非窗口坐标