简体   繁体   中英

HTML5 Canvas Image Move Left Right Up Down with Buttons

I am trying to create an online image editor using HTML5 and getting issue while perform image move with buttons. It does the move with mouse drag but couldn't fix it for buttons. I want to make it work with Move Up, Move Down, Move Right, Move Left Buttons.

jQuery('#moveUp').click(function () {
    var rect = canvas.getBoundingClientRect();

    var x = rect.left;
    var y = rect.top + 1;

    console.log(x);
    console.log(y);
});

Here is my current program. Fiddle Project

Try using image instead of canvas .

jQuery('#moveUp').click(function () {
var rect = image.getBoundingClientRect();
var x = rect.left;
var y = rect.top - 1;
clear();
element.translate(x, y);
drawImage();
});

...or if you prefer a function in order to not having to repeat yourself:

function move(direction) {
  var rect = image.getBoundingClientRect();
  var x = rect.left;
  var y = rect.top;
  var dist = 5 //set distance

  switch (direction) {
    case 'up':
        y -= dist;
      break;
    case 'down':
        y += dist;
      break; 
    case 'left':
        x -= dist;
      break;
    case 'right':
        x += dist;
      break; 
  };

  clear();
    element.translate(x, y);
  drawImage();
};

jQuery('#moveUp').click(function () {
    move('up');
});


jQuery('#moveDown').click(function () {
    move('down');
});

jQuery('#moveLeft').click(function () {
    move('left');
});

jQuery('#moveRight').click(function () {
    move('right');
});

Regarding keys, check this one out: https://api.jquery.com/keypress/ - example (if you decide to use the function I created above):

$(document).keydown(function () {
     move('down');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM