Dragging

Task

Create some sprites which can be dragged around. The z-order of the sprites is automatically adjusted, the clicked sprite gets to the top.

Result

JavaScript

// Demo 4

const grayFrog = makeGrayFrogLibrary();

function start() {
    // Load images and start demo when loading has finished    
    let ip = new grayFrog.ImagePreloader();
    ip.preloadImages(
        [
            { name: 'grid', source: 'images/grid.png' },
            { name: 'blueBall', source: 'images/blueBall.png' }
        ],
        () => demo(ip.imageDictionary)
    );
}

function demo(imageDictionary) {
    // Initialize canvas, controller, and scene
    let canvas = document.getElementById('demoCanvas');
    let controller = new grayFrog.Controller(canvas, true);
    let scene = controller.makeImageScene('main', imageDictionary.grid);
    controller.scene = scene;

    // User drawn sprite
    let rect1 = new grayFrog.DrawnSprite(
        'blueRect', scene.midX - 200, scene.midY, 100, 100);
    rect1.customDraw = function() {
        this.drawRectangleOutline('#0000cc', '#000000', 4, 1, 1);
    };
    // Bump when selected
    rect1.expandOnSelection = true;
    scene.addChild(rect1);

    // Another user drawn sprite
    let rect2 = new grayFrog.DrawnSprite(
        'redRect', scene.midX + 200, scene.midY, 200, 200);
    rect2.customDraw = function() {
        this.drawRectangleOutline('#cc0000', '#000000', 1, 0.5, 0.5);
    };
    scene.addChild(rect2);
    
    // Enable sprites for dragging
    rect1.uiEnabled = true;
    rect1.draggable = true;
    rect2.uiEnabled = true;
    rect2.draggable = true;

    // Start the game loop
    controller.start();
}