Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make clickable points in html5 canvas?

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.

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

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

like image 331
Googlebot Avatar asked May 19 '12 14:05

Googlebot


People also ask

Can you put a button on a canvas in HTML?

You can, however, position your buttons absolutely over top of a canvas or render areas in your canvas that 'look' like buttons and handle the events yourself (a lot of work).

How do I add HTML elements to canvas?

According to the HTML specification you can't access the elements of the Canvas. You can get its context, and draw in it manipulate it, but that is all. BUT, you can put both the Canvas and the html element in the same div with a a position: relative and then set the canvas and the other element to position: absolute .


2 Answers

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.

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 )
}
like image 69
Parth Thakkar Avatar answered Sep 30 '22 21:09

Parth Thakkar


You could use a framework like EaselJS which abstracts all the hard work of handling mouse events on objects that you add to a canvas.

like image 37
Neil Avatar answered Sep 30 '22 21:09

Neil