触摸事件初始坐标

时间:2013-08-15 22:35:01

标签: javascript canvas touch

我正在寻找答案,但无法找到答案。我的问题是:

当我触摸它时,我需要一个物体出现在画布上,当我取消触摸事件时,我需要消失(抬起我的手指)。 但是,我需要对象具有原始触摸位置的初始坐标,这意味着我不希望它用我的手指移动。

var can = document.getElementById('can');
var ctx = can.getContext('2d');

var WIDTH = can.width;
var HEIGHT = can.height;
var canX;
var canY;
var mouseIsDown = 0; 
var requestAnimFrame =  window.requestAnimationFrame ||
                    window.webkitRequestAnimationFrame ||
                    window.mozRequestAnimationFrame ||
                    window.oRequestAnimationFrame ||
                    window.msRequestAnimationFrame;


var image = new Image();
image.src = '1.png';


function init(){
    can.addEventListener("mousedown", mouseDown, false);
    can.addEventListener("mousemove", mouseXY, false);

    document.body.addEventListener("mouseup", mouseUp, false);
    loop();
}


function mouseUp() {
    mouseIsDown = 0;
    mouseXY();
}


function mouseDown() {
    mouseIsDown = 1;
    mouseXY();
}


function mouseXY(e) {
    if (!e)
        e = event;
    canX = e.pageX - can.offsetLeft;
    canY = e.pageY - can.offsetTop;
}


function loop(){
    if(mouseIsDown===1){
        draw();
    } else 
    ctx.clearRect(0,0,WIDTH, HEIGHT);
    requestAnimFrame(loop);
}


function draw(){
    ctx.clearRect(0,0,WIDTH, HEIGHT);
    ctx.drawImage(image,0,0,40,40,canX-20,canY-20,40,40);
}

1 个答案:

答案 0 :(得分:0)

您需要将初始鼠标/触摸位置存储在一对单独的变量中。

var initialCanX, initialCanY;

function mouseDown(e) {
    mouseIsDown = 1;

    initialCanX = e.pageX - can.offsetLeft;
    initialCanY = e.pageY - can.offsetTop;

    mouseXY(e);
}

然后,在绘图功能中,使用这些坐标绘制第二个图像。

function draw(){
    ctx.clearRect(0, 0, WIDTH, HEIGHT);
    ctx.drawImage(image, canX, canY); // the moving image
    ctx.drawImage(image2, initialCanX, initialCanY); // the static image
}