我想寫一些JavaScript,通過拖動鼠標繪製一條線,然後當您釋放左鍵單擊時將其刪除。正確使用onmousemove
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.onload = function() {
window.stop = false
window.canvas = document.getElementById("e");
window.context = canvas.getContext("2d");
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
window.pos = Shift();
}
function Shift() {
e = window.event
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop;
+ document.documentElement.scrollTop;
}
posx -= document.getElementById('e').offsetLeft;
posy -= document.getElementById('e').offsetTop;
return[posx,posy];
}
function up(){
document.getElementById('e').onmousemove = null;
canvas.width = canvas.width;
}
function mov(){
canvas.width = canvas.width;
window.pos = Shift();
context.moveTo(window.start[0],window.start[1]);
context.lineTo(pos[0],pos[1]);
context.stroke();
}
function down(){
window.start = Shift();
document.getElementById('e').onmousemove = "mov()";
}
</script>
</head>
<body>
<canvas id="e" onMouseDown="down()" onmousemove="" onMouseup="up()"></canvas>
</body>
</html>
此示例不起作用並且不會引發錯誤。如果
document.getElementById('e').onmousemove = "mov()";
被註釋掉和的OnMouseMove設置爲
onmousemove="mov()"
那麼它的工作原理,但很明顯的線路只能抽一次。 FireFox中也沒有例子。在Chrome中進行測試。