白板效果的原理其實單純得令人意外:在滑鼠移動的位置放一個小圓點,點點相連就成了線條。
<script type="text/javascript">
var ball;
var mouseX = 100;
var mouseY = 100;
function draw(){
ball = document.createElement("span");
ball.style.position = "absolute";
ball.style.color = "#FF0000";
ball.style.zIndex = 999999999; // 蓋在其他內容之上
ball.innerHTML = "●"; // 用實心圓點當筆跡
document.body.appendChild(ball);
ball.style["left"] = mouseX + "px";
ball.style["top"] = mouseY + "px";
}
// 取得滑鼠在文件中的座標(跨瀏覽器)
function MousePos(e)
{
e = e || window.event;
var x, y;
if (!document.all){
x = e.pageX;
y = e.pageY;
}
else{
x = event.clientX + document.documentElement.scrollLeft;
y = event.clientY + document.documentElement.scrollTop;
}
return {x: x, y: y};
}
function setXY(e)
{
e = e || window.event;
var pos = MousePos(e);
mouseX = pos.x;
mouseY = pos.y;
draw();
}
window.onload = function(){
document.documentElement.onmousemove = function(e){
e = e || window.event;
setXY(e);
};
}
</script>
兩個關鍵點:zIndex 設得夠大,筆跡才不會被頁面其他元素蓋住;MousePos() 則要處理 IE 與標準瀏覽器的座標差異——IE 的 clientX/clientY 是相對於視窗,必須加上捲動量才是文件座標,而 pageX/pageY 本身就是文件座標。
想再往前做的話,可以改成用 canvas 搭配 lineTo 繪製連續線段,效能會比瘋狂新增 DOM 節點好上許多,也能自然支援清空、改筆色、調整粗細等功能。