How to move an image that I am inserting canvas with the mouse

2

Could you please help me, what I want to happen is that I can insert an image that is canvas and that image move it with the mouse over a box ... This inserts but when you click on the image, it disappears . THANK YOU !!!

document.getElementById('inp').onchange = function (e) {
   var img = new Image();
   img.onload = draw;
   img.onerror = failed;
   img.src = URL.createObjectURL(this.files[0]);
   };
  function draw() {
   var canvas = document.getElementById('upper-canvas');
   canvas.width = this.width;
   canvas.height = this.height;
   var ctx = canvas.getContext('2d');
   ctx.drawImage(this, 0, 0);

   var down = false;

  ctx.canvas.addEventListener('mousedown', function () { 
      down = true; 
  }, false);
  ctx.canvas.addEventListener('mouseup', function () { 
      down = false; 
  }, false);
  ctx.canvas.addEventListener('mousemove', function (event) {
      if (down){
          clear();
          ctx.drawImage(event.clientX - this.offsetLeft,
          event.clientY - this.offsetTop, 50, 50);
      }
  }, false);

  function clear(){
  ctx.clearRect(0, 0, canvas.width, canvas.height);

      ctx.fillRect(200, 200, 0, 200);     
  }
   }
  function failed() {
      console.error("El archivo proporcionado no se pudo cargar como un medio de imagen");
  }
<div class="col-md-2" style="width: 50px; height: 30px;">
<input type="file" id="inp"></input></div>                               
<div id="canvas" style="width: 400px; height: 400px; background-color: blue;">
<canvas id="upper-canvas" style="position: absolute; width: 50px; height: 50px;  left:15px; top: 45px; user-select: none; cursor: default;"></canvas>
</div>  
    
asked by Elena 26.09.2018 в 08:21
source

1 answer

1

I made some changes to your code, mainly I changed the canvas size from 50px to 500px, because since I have to move an image I need more space. But you can do it again for 50px if you need it.

What have I done?

  • I have added a function that detects the position of the mouse on the canvas:
  • function oMousePos(canvas, evt) {
      var ClientRect = canvas.getBoundingClientRect();
      return {
        //objeto
        x: Math.round(evt.clientX - ClientRect.left),
        y: Math.round(evt.clientY - ClientRect.top)
      };
    }
    

    This function returns an object that I save in a variable var m . I also need to save the image in a global variable, since I am going to reuse it later. Two other variables are responsible for keeping the distance between the point of grip and the origin of the image in x and y.

    I hope it's what you need.

    An observation: I wanted to leave the code very similar to what you have done. I would have done it a little differently.

    var m = { x: 0, y: 0 }; // la posición del ratón
    var img,// la imagen
        // distancia entre el punto de agarre y el origen de la imagen en x e y
      dx = 0,
      dy = 0;
    
    document.getElementById("inp").onchange = function(e) {
      img = new Image();
      img.onload = draw;
      img.onerror = failed;
      img.src = URL.createObjectURL(this.files[0]);
    };
    
    function draw() {
      var canvas = document.getElementById("upper-canvas");
      var cw = (canvas.width = 500);
      var ch = (canvas.height = 500);
      var ctx = canvas.getContext("2d");
      ctx.drawImage(this, 0, 0);
    
      var down = false;
    
      canvas.addEventListener(
        "mousedown",
        function() {
          down = true;
          var punto_de_agarre = oMousePos(canvas, event);
          dx -= punto_de_agarre.x;
          dy -= punto_de_agarre.y;
        },
        false
      );
      canvas.addEventListener(
        "mouseup",
        function() {
          down = false;
          m = oMousePos(canvas, event);
          dx += m.x;
          dy += m.y;
        },
        false
      );
      canvas.addEventListener(
        "mousemove",
        function(event) {
          if (down) {
            clear();
            m = oMousePos(canvas, event);
            ctx.drawImage(img, m.x + dx, m.y + dy);
          }
        },
        false
      );
    
      function clear() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        //ctx.fillRect(200, 200, 0, 200);
      }
    }
    function failed() {
      console.error(
        "El archivo proporcionado no se pudo cargar como un medio de imagen"
      );
    }
    
    function oMousePos(canvas, evt) {
      var ClientRect = canvas.getBoundingClientRect();
      return {
        //objeto
        x: Math.round(evt.clientX - ClientRect.left),
        y: Math.round(evt.clientY - ClientRect.top)
      };
    }
    canvas{position: absolute; width: 500px; height: 500px;  left:15px; top: 45px; user-select: none; cursor: default; border:1px solid #d9d9d9;}
    #canvas{background-color: blue;}
    <div class="col-md-2">
    <input type="file" id="inp"></input></div>                               
    <div id="canvas">
    <canvas id="upper-canvas"></canvas>
    </div> 
        
    answered by 26.09.2018 в 09:25