用键盘移动kineticJS形状

时间:2014-05-10 12:13:15

标签: keyboard html5-canvas kineticjs shape

我想用键盘箭头移动一些形状。我已经阅读了一些教程,但到目前为止似乎没有任何帮助。我认为问题在于我是如何处理键盘事件的,所以请看一下。

<div id="fullscreenDiv"/>

<script defer="defer">
    var stage = new Kinetic.Stage({
        container: 'fullscreenDiv',
        width: 1180,
        height: 700
    });

    var layer = new Kinetic.Layer();

    var gamepart = new Kinetic.Rect({
        x: 0,
        y: 0,
        width: 1180,
        height: 500,
        fill: 'red',
        stroke: 'black',
        strokeWidth: 4
    });

    var statuspart = new Kinetic.Rect({
        x: 0,
        y: 500,
        width: 1180,
        height: 100,
        fill: 'blue',
        stroke: 'black',
        strokeWidth: 4
    });

    var box1 = new Kinetic.Rect({
        x: 100,
        y: 225,
        width: 130,
        height: 90,
        fill: 'white',
        stroke: 'black',
        strokeWidth: 3
    });

    var box2 = new Kinetic.Rect({
        x: 400,
        y: 225,
        width: 130,
        height: 90,
        fill: 'white',
        stroke: 'black',
        strokeWidth: 3
    });

    var line12 = new Kinetic.Line({
        points: [230, 270, 400, 270],
        stroke: 'black',
        strokeWidth: 3
    });

    var box3 = new Kinetic.Rect({
        x: 1400,
        y: 225,
        width: 130,
        height: 90,
        fill: 'white',
        stroke: 'black',
        strokeWidth: 3
    });

    var line23 = new Kinetic.Line({
        points: [530, 270, 1400, 270],
        stroke: 'black',
        strokeWidth: 3
    });

    // add the shape to the layer
    layer.add(gamepart);
    layer.add(statuspart);
    layer.add(box1);
    layer.add(box2);
    layer.add(line12);
    layer.add(box3);
    layer.add(line23);

    // add the layer to the stage
    stage.add(layer);

    layer.draw();


    window.addEventListener('keydown', function(e) {
        if (e.keyCode == 37) //Left Arrow Key
            box1.attrs.x -= 10;
        if (e.keyCode == 38) //Up Arrow Key
            box1.attrs.y += 10;
        if (e.keyCode == 39) //Right Arrow Key
            box1.x += 10;
        if (e.keyCode == 40) //Top Arrow Key
            box1.attributes.x -= 10;

        stage.draw();
    });


</script>

修改

这是网页的图片,我想用内部的白色移动rectallgles。

enter image description here

1 个答案:

答案 0 :(得分:1)

你非常接近。只需使用其他API来更改属性:

    if (e.keyCode == 37) //Left Arrow Key
        box1.x(box1.x() - 10);
    if (e.keyCode == 38) //Up Arrow Key
        box1.y(box1.y() + 10);
    if (e.keyCode == 39) //Right Arrow Key
        box1.x(box1.x() + 10);