Lucy
Lucy

Reputation: 1852

Find Position of Objects in Canvas

I'm dragging and dropping an image from a toolbar onto a canvas.The user can drag&drop that same image from the toolbar multiple times.The user can also remove a particular object on double click as shown in the link below..

http://jsfiddle.net/gkefk/26/

I want to record the position of these objects on page load and also after moving them around in the canvas.For this i'm adding an event listener and a function which will show the positions of all the objects on button click

myButton.addEventListener('click', position);

The JS function used to calculate position of the objects..

function Rectangle(props) {
    var posX = this.posX = props.x;
    var posY = this.posY = props.y;

    this.width = props.width;
    this.height = props.height;
    this.fill = props.fill;
    this.isDragging = props.isDragging;

    this.draw = function() {
        ctx.fillStyle = this.fill;
        ctx.fillRect(this.posX, this.posY, this.width, this.height);

    }
}

Even though I'm adding the above JS function I'm not getting the output on button click..I don't know where i'm going wrong...Is there a simpler way of doing this in jQuery??

The link containing the above JS function

http://jsfiddle.net/gkefk/27/

Upvotes: 0

Views: 1350

Answers (1)

markE
markE

Reputation: 105015

Take a few minutes to review what you've put together.

Your top toolbar holds draggable DOM elements.

Once any draggable DOM element has been released on the Kinetic Canvas, you are creating a new Kinetic.Image at the same location as the dropped DOM element. This Kinetic.Image cannot be accessed by jQuery because it is not a DOM element -- it is a Kinetic.Image node.

Therefore, you must access that new Kinetic.Image using KineticJS, not jQuery.

In your dragDrop, you give the Kinetic.Image a name property. KineticJS name properties are like classes in Html/CSS. This means if drag more than 1 image onto the canvas, you will have 2 images with the same name. This is probably not what you intend.

Also, the name you are assigning each Kinetic.Image is "house.png" which you fetch from the drop element's "url" data property. This is probably not what you intend.

Instead, if you assign each of your new Kinetic.Images a unique id property then you can use stage.find to get the specific Kinetic.Image with a specified id. The Kinetic id property is like the Html/CSS id property. Then you can get any desired Kinetic.Image's x,y,width,height like this:

var myDesiredKineticImage = stage.find("#"+myDesiredId);

var x=myDesiredKineticImage.x();
var y=myDesiredKineticImage.y();
var width=myDesiredKineticImage.width();
var height=myDesiredKineticImage.height());

Upvotes: 2

Related Questions