html5捕获画布中的鼠标点击

时间:2013-06-10 03:24:48

标签: html5 javascript-events

这是简化的代码,考虑了nycnik建议的答案。代码效果更好,但是比例和偏移仍然是关闭的。单击拖动和释放,绘制的线条似乎约为2关。

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="st.css" media="all"/>
    <script>
var x, y;
function getXY(canvas, e) {
    var rect = canvas.getBoundingClientRect();
    return [e.clientX - rect.left, e.clientY - rect.top];
}

function move(ca, e) {


}

function mark(ca, e) {
    [x,y] = getXY(ca, e);
}

function clickDrag(ca, e) {
    var c = ca.getContext("2d");
    var x2, y2;
    [x2,y2] = getXY(ca, e);
    c.fillStyle='#00FF80';
    c.lineStyle='#FFFF80';
    c.moveTo(x,y);
    c.lineTo(x2,y2);
    c.stroke();  
}
    </script>
  </head>
  <body>
    <div class="bg">
      <canvas id="q13g" onmousedown="mark(this,event)" onmouseup="clickDrag(this, event)">
      </canvas>
    </div>
  </body>
</html>

1 个答案:

答案 0 :(得分:3)

您只需要使用您看到的clientX和边界矩形进行转换,如下所示,并在本教程中进行:

function getMousePos(canvas, evt) {
        var rect = canvas.getBoundingClientRect();
        return {
          x: evt.clientX - rect.left,
          y: evt.clientY - rect.top
        };
      }

http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/