使用KineticJS在舞台上动态添加圆圈

时间:2014-07-31 13:51:16

标签: javascript kineticjs

我有以下代码。我希望用户单击要添加的舞台对象和圆圈。 我的代码

var stage, backgroundLayer, backgroundImage, imageObj;
var pointLayer, pointObj;
var points = {};

imageObj = new Image();
imageObj.src = "../media/proline_ap_pa_ceph__17839_1340650087_1280_1280.png"

window.onload = function (){
    stage = new Kinetic.Stage({
        width:800,
        height:600,
        container:'container'
    });

    pointLayer = new Kinetic.Layer({
        width:stage.width,
        height:stage.height
    });

    console.log(backgroundLayer);
    console.log("successfully created stage")
    stage.add(backgroundLayer);
    stage.add(pointLayer);
    document.getElementById('hide').addEventListener('click', function(){
        backgroundImage.hide();
        backgroundLayer.draw();

    });
    document.getElementById('show').addEventListener('click', function(){
        backgroundImage.show();
        backgroundLayer.draw();
    });
    stage.on('click', function (event){
        console.log(event);
        console.log("clicking on stage");
        var point = new Kinetic.Circle({
            fill:"black",
            radius:40,
            width:30,
            height:30,
            x:event.pageX,
            y:event.pageY
        });

        console.log(point);
        pointLayer.add(point);
        pointLayer.draw();
        stage.draw();

    });

};


backgroundLayer = new Kinetic.Layer({
    width:800,
    height:600,
    visible:true
});



imageObj.onload = function (){
    console.log("Image loaded adding kinetic image")
    backgroundImage = new Kinetic.Image({
        image:imageObj,
        width:800,
        height:600
    });
    console.log("finised image loading");
    console.log("Adding image to background Layer");
    backgroundLayer.add(backgroundImage);

}

但我的舞台上没有显示圆圈,加上event.target似乎是Image的类型,而我点击了舞台。我想这是因为图像位于舞台上首先添加的图层顶部。

1 个答案:

答案 0 :(得分:1)

收听contentClick事件而不是click事件:

stage.on('contentClick',function(){
    var pos=stage.getPointerPosition();
    var mouseX=parseInt(pos.x);
    var mouseY=parseInt(pos.y);

    // and now add your circle

});