0

我正在使用 Cordova + Onsen Ui 2 + javascript 开发一个应用程序,但我在从 javascript 移动事件中获取坐标 X 和 Y 时遇到问题。我尝试了 mousemove(它没有触发)和拖动(但是当我尝试从事件对象获取 pageX 或 clientX 时我得到了未定义)。我还没有找到任何关于用画布绘图的例子。提前谢谢大家!

Javascript:

var canvasListener = function(){    
    canvas = document.getElementById("canvas");    
    canvas.addEventListener('mousedown', function(event){
        var coordinates = painting(event);           
    });
    canvas.addEventListener('drag', function(event){
           var coordinates = painting(event); 
    });
    canvas.addEventListener('mouseup', function(event){
        var coordinates = painting(event);
    });
}

function painting(event){
    var x = event.clientX;
    var y = event.clientY;
    var touchX = x - signatureCanvas.offsetLeft;
    var touchY = y - signatureCanvas.offsetTop;
    var localCoordinates;    
    if(event.type == 'mouseup'){
        localCoordinates = {
            x: 0,
            y: 0
        };
    }else{
        localCoordinates = {
            x: touchX,
            y: touchY
        };
    }    
    return localCoordinates;
}

html:

<canvas id="canvas"></canvas>
4

3 回答 3

0

尝试这个..

var damagesCanvas = document.getElementById('damagesCanvas');

damagesCanvas.addEventListener('click', function (evt) {
    var pos = getMousePos(damagesCanvas, evt);
}, false);

function getMousePos(damagesCanvas, evt) {
    var rect = damagesCanvas.getBoundingClientRect();
    return {
        X: evt.clientX - rect.left,
        Y: evt.clientY - rect.top
    };
}
于 2016-07-09T17:58:16.903 回答
0

试试这个代码。在画布上移动鼠标时,当前鼠标(x,y)坐标将打印在屏幕上。希望这个逻辑只有你在寻找。

提琴手

HTML

<canvas width="300" height="225"></canvas>

<span class="first">Move the mouse over the div.</span>
<span></span>

JS

var canvas = $('canvas');
canvas.mousemove(function(e){
    var pageCrds = '('+ e.pageX +', '+ e.pageY +')',
        clientCrds = '('+ e.clientX +', '+ e.clientY +')';

    $('span:first').text('(e.pageX, e.pageY) - '+ pageCrds);    
    $('span:last').text('(e.clientX, e.clientY) - '+ clientCrds);

});
于 2016-05-19T13:37:48.853 回答
0

通常你会想要使用event.clientX,event.clientY和 的结果canvas.getBoundingClientRect();。这是一个使用 MouseMove 事件的示例:

can.addEventListener('mousemove', function(e) {
  var canwidth = can.width;
  var canheight = can.height;
  var bbox = can.getBoundingClientRect();
  var mx = e.clientX - bbox.left * (canwidth / bbox.width);
  var my = e.clientY - bbox.top * (canheight / bbox.height);

  // output it to see results:
  ctx.fillRect(mx, my, 1, 1);
})

这适用于所有平台上的所有鼠标/触摸事件,并适应许多困难的 CSS 情况。

现场示例:http ://codepen.io/simonsarris/pen/NNVQpj?editors=1010

于 2016-05-19T19:37:26.367 回答