I want to move my text object within a rectangle on canvas using easeljs. I would like the text object to stop moving as soon as it touches the rectangle boundary. How can I do this in easeljs? Or is better using another framework? Or layered canvases?
My rectangle boundary on the canvas loos like this:
var textBoundary = new createjs.Shape();
textBoundary.graphics.beginStroke("#999");
textBoundary.graphics.setStrokeStyle(1);
textBoundary.snapToPixel = true;
textBoundary.graphics.drawRect(82, 130, 149, 240);
textBoundary.setBounds(82, 130, 149, 240);
stage.addChild(textBoundary);
stage.update();
My dragger code looks like this until now:
var textFront = new createjs.Text();
var t = document.getElementById("TextInput1").value;
textFront.text = t;
var draggerFront = new createjs.Container();
draggerFront.x = 160;
draggerFront.y = 130;
draggerFront.addChild(textVorne,tb);
stage.addChild(draggerFront);
draggerFront.on("pressmove",function(evt) {
evt.currentTarget.x = evt.stageX ; // here I have no idea what to
evt.currentTarget.y = evt.stageY ; // do when the dragger reaches
draggerFront.mouseMoveOutside = false; // boundary
stage.update();
});
stage.update();
Thanks in advance for any help or pointers in the right direction.
I repurposed your example so it works in jsfiddle.net, but I don't know if it is what you had in mind. http://jsfiddle.net/lannymcnie/xrqatyLs
If you are trying to drag the text, and constrain it to the box, here are the steps I took:
Math.max(min, Math.min(max, val))
to do this.Here is a modified example that works. This version constrains the text's "position" to the box. This means it will draw outside the box on the bottom and right. http://jsfiddle.net/lannymcnie/xrqatyLs/1/
To constrain the whole thing, subtract the text size from the "min" position. http://jsfiddle.net/lannymcnie/xrqatyLs/2/
textFront.on("pressmove",function(evt) {
evt.currentTarget.x = Math.max(bounds.x, Math.min(bounds.x+bounds.width-textBounds.width, evt.stageX));
evt.currentTarget.y = Math.max(bounds.y, Math.min(bounds.y+bounds.height-textBounds.height, evt.stageY));
stage.update();
});
A few additional things I would do to make in nicer:
textBounds.x/y
so you can use other text alignment modes. This demo assumes the text is drawing from the top/left.Hope that helps.