我正在尝试写一些JavaScript,通过拖动鼠标来画一条线,然后在你松开左键时删除它。
<!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中测试。
3条答案
按热度按时间mtb9vblg1#
更改此内容:
对此:
你想把
.onmousemove
赋给一个函数引用,而不是一个字符串。注意这里没有括号:如果你赋值...onmousemove = mov()
,它将运行mov()
函数,并将onmousemove
赋值给函数的返回值(未定义,对于这个特定的函数),如果没有括号,它将赋值给函数本身。euoag5mw2#
使用
做了一些修复,但它是疯狂的代码:)
3z6pesqy3#
你的函数赋值不正确
http://jsfiddle.net/wmTYr/