Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fabric js moving image with keyboard

Im creating simple tool with fabric.js and I need to add functionality to move object with keyboard.And I'm stuck.For the moment i log in to the console the keyboard events,so I know it works.but I don't know how to add this fucntionality to my canvas image.And help?

$(function(){
    var canvas = new fabric.Canvas('imageCanvas', {
        backgroundColor: 'rgba(255, 255, 255, 0)'
    });
    var imageLoader = document.getElementById('imageLoader');
    imageLoader.addEventListener('change', handleImage, false);

    function handleImage(e) {
        var reader = new FileReader();
        reader.onload = function (event) {
            var img = new Image();
            img.onload = function () {
                var imgInstance = new fabric.Image(img, {

                })
                canvas.add(imgInstance);
            }
            img.src = event.target.result;

        }
        reader.readAsDataURL(e.target.files[0]);
    }

    canvas.on('mouse:down', function(options) {
      console.log(options.e.clientX, options.e.clientY);
    });

    var canvasWrapper = document.getElementById('canvasWrapper');
    canvasWrapper.tabIndex = 1000;
    canvasWrapper.addEventListener("keydown", doKeyDown, false);

    function doKeyDown(e) {
        document.onkeydown = function(e) {
            switch (e.keyCode) {
                case 38:  /* Up arrow was pressed */
                    console.log('up works')
                  break;
                case 40:  /* Down arrow was pressed */
                    console.log('down works')
                  break;
                case 37:  /* Left arrow was pressed */
                    console.log('left works')
                  break;
                case 39:  /* Right arrow was pressed */
                   console.log('right works')
                  break;
              }
        }
    }

    var imageSaver = document.getElementById('imageSaver');
    imageSaver.addEventListener('click', imageBorder, false);
    imageSaver.addEventListener('click', saveImage, false);

    function imageBorder(e) {
        canvas.item(0).hasControls = canvas.item(0).hasBorders = false;
    }

    function saveImage(e) {
        this.href = canvas.toDataURL({
            format: 'png',
            quality: 1
        });
        this.download = 'test.png'
        if(saveImage) {
            location.reload();
        }else {
            alert('somtehing went wrong')
        }
    }

});
like image 558
burakukula Avatar asked Jul 14 '14 09:07

burakukula


1 Answers

Try for example on case 39:

canvas.getActiveObject().left += 5;

And then maybe canvas.renderAll()

like image 173
Joaozinho das Couves Avatar answered Sep 27 '22 17:09

Joaozinho das Couves