正确使用onmousemove [英] proper use of onmousemove

查看:76
本文介绍了正确使用onmousemove的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一些Javascript,通过拖动鼠标来画一条线,然后在放开鼠标左键时将其删除.

I am trying to write some javascript that draws a line by dragging the mouse, and then removes it when you let go of left click.

<!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>

此示例不起作用,并且不会引发任何错误.如果

This example does not work and throws no errors. If

   document.getElementById('e').onmousemove = "mov()";

已被注释掉,并且onmousemove设置为

is commented out and onmousemove is set to

onmousemove="mov()"

然后它可以工作,但是很明显,一条线只能绘制一次.同样,两个示例都无法在FireFox中使用.在Chrome中进行了测试.

then it works, but obviously a line can only be drawn once. Also neither of the examples worked in FireFox. Tested in Chrome.

推荐答案

更改此内容:

document.getElementById('e').onmousemove = "mov()"; 

对此:

document.getElementById('e').onmousemove = mov;

您想将 .onmousemove 分配给函数引用,而不是字符串.请注意,没有括号:如果您分配 ... onmousemove = mov(),它将运行 mov()函数并分配 onmousemove 返回函数的返回值(此特定函数未定义).没有括号,它将其分配给函数本身.

You want to assign .onmousemove to a function reference, not to a string. Note that there are no parentheses: if you assign ...onmousemove = mov() it will run the mov() function and assign onmousemove to the return from the function (undefined, with this particular function). Without the parentheses it assigns it to the function itself.

这篇关于正确使用onmousemove的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆