如何使可点击点在html5画布? [英] How to make clickable points in html5 canvas?

查看:120
本文介绍了如何使可点击点在html5画布?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩一个简单教程画布中绘制线条 HTML5 。因为它是基于jQuery的,很容易添加大量的效果到绘图。

I am playing with a simple tutorial for drawing line in HTML5 canvas. Since, it is based on jQuery, it is easy to add lots of effects to the drawing.

如何使点可点击/悬停添加jquery效果点击/ hover(mouseenter / mouseleave)?点由

How can I make the point clickable/hoverable to add jquery effects upon click/hover (mouseenter/mouseleave)? The points are drawn by

c.fillStyle = '#333';

for(var i = 0; i < data.values.length; i ++) {
    c.beginPath();
    c.arc(getXPixel(i), getYPixel(data.values[i].Y), 4, 0, Math.PI * 2, true);
    c.fill();
}

如何添加jquery selector?基本上,我想点击或悬停时显示点坐标

How to add jquery selector? Basically, I want to show the point coordinates upon click or hover.

推荐答案

问题是, jQuery使用DOM而不是画布上的图纸。你需要做的是将这些点存储在某处,并悬停在canvas元素上,检查鼠标相对于画布的坐标(即如果将鼠标放在画布的左上角,coords是[ 0,0])在点/形状的区域内。

The problem is that jQuery works with DOM and not drawings on canvas. What you need to do is to store those points somewhere and on hovering over the canvas element, check if the coordinates of the mouse relative to the canvas ( i.e. if you place the mouse over the top-left corner of the canvas, coords are [0,0] ) are within the area of the point/shape. If so, the point is hovered over by the mouse and you can display the effect.

Puedocode以便更好地理解:

Psuedocode to understand better:

// adding shapes to the canvas
var shapes = [];  // make that rects for simplicity.
For (condition):
    shapes.push ( new Rect(x,y,width,height) );
    canvas.rect( x, y, width, height );

// testing hover.
$("#canvas").mousemove(function(e) {
    var offsetX = e.pageX - $(this).position().left;
    var offsetY = e.pageY - $(this).position().top;

    Foreach shape in shapes:
        if( shape.contains(offsetX, offsetY) )    // a fictious method, implement it yourself...lookup for collision detection; not exactly that but something like that...
            Mouse hovers! do something great.
});

好的,也许要找出一个点是否包含在一个矩形中, :

Ok, maybe to find out if a point is contained within a rectangle, you can use something like this:

function contains(rect, x, y) {
    return (x >= rect.x &&
            x <= rect.x + rect.width &&
            y >= rect.y && 
            y <= rect.y + rect.height )
}

这篇关于如何使可点击点在html5画布?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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