在KineticJS中创建一个带有mousedown事件的矩形

时间:2012-12-13 19:05:54

标签: javascript html5 html5-canvas kineticjs

我正在尝试使用带有mousedown和拖动事件的KineticJS创建一个矩形形状,但没有太多运气。有没有人做过类似的事情?

1 个答案:

答案 0 :(得分:3)

http://jsfiddle.net/AYHSM/6/

var stage = new Kinetic.Stage({
    container: 'container',
    width: 600,
    height: 400
});

var layer = new Kinetic.Layer();
layer.add(new Kinetic.Rect({
    x:0,
    y:0,
    width:600,
    height:400
}));  // this rect will allow us to use mouse events on the layer. There's probably a better way to do this, but I don't know it.
stage.add(layer);
var rect, down = false; // down is a flag to know whether or not the mouse button is down so that we only resize the new rect when it is down.

layer.on("mousedown", function(e) {

    down = true;
    var r = Math.round(Math.random()*255),
        g = Math.round(Math.random()*255),
        b = Math.round(Math.random()*255);
    rect = new Kinetic.Rect({
        x: e.layerX,
        y: e.layerY,
        width: 11,
        height: 1,
        fill: 'rgb('+r+','+g+','+b+')',
        stroke: 'black',
        strokeWidth: 4
    });
    layer.add(rect);
});

layer.on("mousemove", function(e) {
    if (!down) return;

    var p = rect.attrs;

    rect.setWidth(e.layerX - p.x);
    rect.setHeight(e.layerY - p.y);
    layer.draw();
});

layer.on("mouseup", function(e) {
    down = false;
});​