Is it possible to add tooltips to image's draw

2019-07-19 23:54发布

问题:

I would like to draw a line or bar graph using HTML5 canvas.

I would like to

  • take in data from an outside source (or hardcode it in for testing purposes)

  • draw the graph

  • Hover over a node/bar and have a tooltip appear displaying the number/relevant data.

So my question is, it is possible to apply tooltips to individual images/lines/anything on a canvas? (I know that the canvas itself can have it's own tooltip)

One solution that I'm sure would work would be to just make each node a separate canvas with it's own tooltip and image but that sounds a bit excessive.

And ideally I would like to use jquery.ui.tooltip, but really I just want to know if anything will work.

    var imageObj = new Image();
    $(imageObj).attr("title","kitten");
    $(imageObj).tooltip();

    imageObj.onload = function(){
    context.drawImage(imageObj, destX, destY, destWidth, destHeight);
    };
    imageObj.src = "BW-kitten.jpg";

I got the outline from here and added what I thought could possibly work.

The kitten draws properly and there are no console errors and all of that good stuff.

回答1:

HTML5 (for lack of a better word) shapes are drawn onto a canvas, and technically don't exist. There are several plugins out there that make use of custom handlers to manage the precise locations of these shapes and add functionality similar to that of regular DOM elements.

I use KineticJS with my HTML5 projects as it follows the simplicity of regular shapes, and allows for complex shapes in an easy manner. Here is a KineticJS example that adds tooltips to their shapes.

You can use Kinetic.Image from the documentation to easily add the image to your stage, and follow the previously linked example on how to add tooltips to the shape.