Question

I draw several shapes on a canvas using the jCanvas library with this function:

var factoryCounter = 1;

$(".atom").click(function() {
    //get element by tag id
    var AtomId = jQuery(this).attr("id");
    var elementRef = "#el" + factoryCounter;
    $("canvas")
    .drawImage({
        source:'images/' + AtomId + '.png',
        layer: true,
        name: "myAtom" + factoryCounter,    //I need this value
          fillStyle: "#36b",
          strokeStyle: '#36b',
          strokeWidth: 0.3,
          x: 36, y: 28,
          width: 45, height: 35,
          radius: 100,
          ccw: true,
          draggable: true,
            click: function(layer) {
                            console.log("name")  //here I need to return "name", but don't know how.

        }                   
    });
    factoryCounter++;

As you can see each shape has its own unique name. I'd like to create a function which returns the name of the selected shape after I click on it with the mouse. I can successful edit the attributes of a shape which NAME is known, like this:

      $("canvas").setLayer("myAtom" + 2, {
    fillStyle: "#36b",
    width: 100, height: 200,
    rotate: 30
    })
         .drawLayers();
    });

But have no idea how to implement shapeSelect() function which returns the NAME of an existing shape by clicking on it.

Was it helpful?

Solution

Alright I asked the guy that did the library and he showed me the right answer. In case you need it, here it is:


Well, rather than having a click event bound to the canvas element, set up a click event for each new jCanvas layer. When you click one of those layers, have the callback function switch between what it's going to do, based on some layer property that you create (such as layer.selected). Here's the basic idea:

    $("canvas").drawImage({
// image properties here...
layer: true,
name: "someLayer",
selected: false,
click: function(layer) {
    if (layer.selected === false) {
        layer.selected = true;
        // do something with the layer name
    } else if (layer.selected === true) {
        layer.selected = false;
        // deselect the layer
    }
 }
});

-Caleb


Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top