1

我正在寻找答案,但找不到任何答案。我的问题是:

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

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);
}
4

1 回答 1

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
}
于 2013-08-17T09:10:38.770 回答