使用EaselJS使用鼠标事件调整画布元素的大小

时间:2011-11-04 15:53:23

标签: javascript jquery html5 canvas easeljs

我尝试将图元绘制到画布上,然后允许用户通过单击并拖动它们来调整它们的大小。我已经使用Kinetic JS库实现了这一点,但我的开发团队正在转向Easel JS。

Here is the code with the Kinetic library.

这很好用。

我在Easel JS中做到了这一点,但这段代码没有做任何事情。画布完全是空白的。我意识到我不确定如何:

  • 调用鼠标事件 - 我在这里尝试将它们附加到DOM元素,如this tutorial
  • 在哪里设置调整大小功能 - 单独的功能?在tick()函数内调用?
  • 抓住鼠标坐标
    var canvas;
var stage;
var rect;

var mousePos = new Point(); 
var update = true;

var rectX = 10;
var rectY = 10;
var rectW = 100;
var rectH = 50;
var rectXOffset = 50;
var rectYOffset = 50;

var newWidth;
var newHeight;

function init() {
    // create stage and point it to the canvas:
    canvas = document.getElementById("testCanvas");
    stage = new Stage(canvas);

    // overlay canvas used to draw target and line
    canvasWrapper = $("#testCanvas");

    // listen for a mouse down event
    canvasWrapper.mousedown(onMouseDown);

    // listen for mouse up event
    canvasWrapper.mouseup(onMouseUp);

    // enable touch interactions if supported on the current device:
    if (Touch.isSupported()) { Touch.enable(stage); }

    // enabled mouse over / out events
    stage.enableMouseOver(10);

    // start drawing instructions
    var rect = new Shape();
    rect.graphics
        .setStrokeStyle(1)
        .beginStroke(Graphics.getRGB(25,25,112,.7))
        .drawRect(rectX,rectY,rectW,rectH);

    // add rectangle to stage
    stage.addChild(rect);

    // render stage
    stage.update();

    // set the tick interval to 24 fps
    Tick.setInterval(1000/24);

    // listen for tick event
    Tick.addListener(window, true);

    // pause
    Tick.setPaused(false);

}

//called when user clicks on canvas
function onMouseDown(e) {

    mousePos.x = e.stageX;
    mousePos.y = e.stageY

    // check to see if mouse is within offset of rectangle
    if(mousePos.x <= (rectW + rectXOffset) || mousePos.y <= (rectH + rectYOffset)) {
        // set update to true
        update = true;

        // unpause tick
        Tick.setPaused(false);

    }

}

function onMouseUp(e) {
    update = false;
    Tick.setPaused(true);
}

function tick() {
    // this set makes it so the stage only re-renders when an event handler indicates a change has happened.
    if (update) {
       if(mousePos.x - rectX < 50) 
       {
        newWidth = 50;
       } else {
        newWidth = mousePos.x - rectX;
       }
       if(mousePos.y - rectY < 50) 
       {
        newHeight = 50;
       } else {
        newHeight = mousePos.y -rectY;
       }
        rectW = newWidth;
        rectH = newHeight;

        rect.clear();

        rect.graphics
        .setStrokeStyle(1)
        .beginStroke(Graphics.getRGB(65,65,65,.7))
        .drawRect(0,0,rectW,rectH);

        // add rectangle to stage
        stage.addChild(rect);

        update = false; // only update once
        stage.update();
    }
}

我知道不应该这么困难,并希望得到任何帮助。

0 个答案:

没有答案