HTML5画布鼠标 [英] HTML5 Canvas Mouse

查看:206
本文介绍了HTML5画布鼠标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

像我这样有:



    function mouseClick(event) {
        ...
    }
    canvas.addEventListener("mousedown", mouseClick, false);
    function drawRect(x, y) {
        context.fillRect(x, y, 16, 16);
    };
    drawRect(10, 10);

如果我点击我的Rect在Canvas得到什么?如果我点击Rect get alert;

How to do something like if I am click on my Rect in Canvas get something? something like If I am click on Rect get alert;

对不起,我的英语。

推荐答案

画布只不过是一个位图。没有记录,在画布上有一个矩形,所以如果你想检测到点击是在一个区域,你画了一个矩形,你必须保持你绘制和测试的区域的记录反对他们。例如:

A canvas is nothing more than a bitmap. There is no record kept that there was a rectangle drawn on the canvas, so if you want to detect that the click was inside an area that you drew a rectangle on, you have to keep a record of the areas you've drawn and test against them. eg:

var rects= [];

function mouseClick(event) {
    // Get position of click relative to canvas. This is not reliable! Requires
    // standards mode, and the canvas not being nested in other offsetParents.
    // Getting page-relative co-ordinates reliably in all cases is outside the
    // scope of this question...
    //
    var x= event.clientX-document.documentElement.scrollLeft-canvas.offsetLeft;
    var y= event.clientY-document.documentElement.scrollTop-canvas.offsetTop;

    // Hit-test each rectangle in the list of those drawn
    //
    for (var i= rects.length; i-->0;) {
        var x0= rects[i][0], y0= rects[i][1], x1= rects[i][2], y1= rects[i][3];
        if (x0<=x && x<x1 && y0<=y && y<y1) {
            alert('you clicked on a rectangle!');
        }
    }
}
function drawRect(x, y) {
    rects.push([x, y, x+16, y+16])
    context.fillRect(x, y, 16, 16);
};
drawRect(10, 10);

如果你做了很多这样的事情,你可能会更好地使用保留模式绘制系统像SVG而不是纯位图画布。在SVG中,您可以直接在矩形对象上侦听点击事件,移动矩形,重新堆叠等。

If you are doing a lot of this sort of thing you are likely to be better off using a retained-mode drawing system like SVG instead of the pure-bitmap Canvas. In SVG you can listen for click events directly on a rectangle object, move the rectangle, re-stack it and so on.

这篇关于HTML5画布鼠标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆