html canvas为mouseup事件设置x和y坐标

时间:2014-04-30 18:12:33

标签: javascript html5-canvas mouseevent

我想知道如何设置拖动图像并在该区域中释放鼠标后发生的事件的X和Y坐标。像游戏一样,你选择三种选择之一。大量教程向您展示了如何执行mouseup事件,但似乎没有人告诉您如何设置事件的坐标。

2 个答案:

答案 0 :(得分:1)

以下是一个示例...... http://jsfiddle.net/m1erickson/qU3gq/

假设您有一个这样的图像,您希望有人点击他们选择的动物:

enter image description here

这就是动物水平排列的方式。

The bird     part of the image starts at x==0   and ends at x==121.
The bear     part of the image starts at x==122 and ends at x==231.
The camel    part of the image starts at x==232 and ends at x==325.
The elephant part of the image starts at x==326 and ends at x==475.
The zebra    part of the image starts at x==476 and ends at x==600.

因此,您可以创建一个代表每只动物的javascript对象并将它们放在一个数组中:

var animals=[];
animals.push({minX:0,maxX:121,name:"Bird"});
animals.push({minX:122,maxX:231,name:"Bear"});
animals.push({minX:232,maxX:325,name:"Camel"});
animals.push({minX:324,maxX:475,name:"Elephant"});
animals.push({minX:476,maxX:600,name:"Zebra"});

然后你可以监听mouseUp事件并计算mouseX& mouseY被释放的鼠标是这样的:

// listen for mouseUp events

canvas.onmouseup=handleMouseup;

// canvas is a reference to the canvas element
// BB is the bounding box of the canvas element (as adjusted for scrolling)

function handleMouseUp(e){

    var BB=canvas.getBoundingClientRect();
    mouseX=parseInt(e.clientX-BB.left);
    mouseY=parseInt(e.clientY-BB.top);

    ... 

在mouseUp中,您可以测试鼠标是否在特定动物区域内释放,如下所示:

var selectedAnimal="None";
for(var i=0;i<animals.length;i++){
    var animal=animals[i];
    if(mouseX>=animal.minX && mouseX<=animal.maxX){
        selectedAnimal=animal.name;
    }
}
alert("You released the mouse over the "+selectedAnimal);

}

答案 1 :(得分:0)

创建一个变量,用作引擎的标志(true / false),表示正在拖动图像,另一个标识图像。释放鼠标时,清除标记。使用jQuery定义鼠标事件方法或在javascript中手动定义。你想要一些代码的例子吗?我希望我理解你的问题。

http://www.html5canvastutorials.com/

这只是我扔在一起的一些伪代码;你应该能够弄清楚如何自己实现它,因为你的大部分问题都是合乎逻辑的。

<script>
    var mouseX = 0;
    var mouseY = 0;
    var imageXDropped = 0; // optional; depends on your logic/algorithm
    var imageYDropped = 0; // optional; depends on your logic/algorithm
    var imageDragging = false;
    $(document).ready(function(){
      $("#myCanvas").mousemove(function(event){
        var rect = $("#myCanvas").getBoundingClientRect();
        mouseX = event.clientX - rect.left;
        mouseY = event.clientY - rect.top;

        if(imageDragging){
          //set image position to mouse position
        }
      });

     //image mousedown function(event){
        imageDragging = true;
     }
     //image mouseup function(event){
        imageDragging = false;
        imageXDropped = event.clientX - $("#myCanvas").getBoundingClientRect().left; (mouse x position)
        imageYDropped = event.clientY - $("#myCanvas").getBoundingClientRect().top; (mouse y position)
     }
    });

</script>