Drag while in background in KineticJs

2019-08-19 04:41发布

问题:

I have two layers generally representing a large background and some content on top of it. I have made the background draggable but when dragged, it covers the content of the other layer. Is it possible to keep it in the background while dragging it?

I have tried binding the drag events with .moveToBottom() for the background group (later added to backgroundLayer) like that:

groupBackground.on('dragstart',function(){
    groupBackground.moveToBottom();
});
groupBackground.on('dragmove',function(){
     groupBackground.moveToBottom();
});
groupBackground.on('dragend',function(){
     groupBackground.moveToBottom();
});

but to no result.

回答1:

You can “draw under” by using the canvas “.globalCompositeOperation”

This will allow your user to drag the background under the foreground.

And you can apply it to KineticJs like this:

layer.getContext().globalCompositeOperation = "destination-over";

Here is code and a Fiddle: http://jsfiddle.net/m1erickson/2GFSE/

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

var layer = new Kinetic.Layer();
stage.add(layer);
var background = new Kinetic.Rect({
    x: stage.getWidth() / 2,
    y: stage.getHeight() / 2,
    width: 250,
    height: 250,
    fill: 'black',
    stroke: 'black',
    strokeWidth: 4,
    draggable: true
});

var foreground = new Kinetic.Ellipse({
    x: stage.getWidth() / 3,
    y: stage.getHeight() / 3,
    radius: {
        x: 50,
        y: 30
    },
    fill: 'red',
    stroke: 'black',
    strokeWidth: 4
});

// add the background and foreground to the layer
layer.add(foreground);
layer.draw();
layer.getContext().globalCompositeOperation = "destination-over";

layer.add(background);
layer.draw();