Подтвердить что ты не робот

Сделать изображение на холсте перетаскиваемым с помощью JavaScript

Мне удалось успешно нарисовать изображение на холсте HTML. Но мне нужно иметь возможность перетаскивать изображение на холст.

Я знаю, что эта функция может быть легко реализована некоторыми библиотеками JavaScript, такими как KinectJS. Но я хочу просто сделать это с помощью простого JavaScript.

window.onload = function(){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var destX = 0;
var destY = 0;
var imageObj = new Image();

imageObj.onload = function(){
  context.drawImage(imageObj, destX, destY);
};
imageObj.src = "westeros.png";
<canvas id="myCanvas" height=1024 width=360></canvas>
4b9b3361

Ответ 1

Для перетаскивания вы обрабатываете 3 события мыши:

  • mousedown - установить флаг, указывающий, что началось перетаскивание.

  • mouseup - очистить флаг перетаскивания, потому что перетаскивание завершено

  • mousemove - если установлен флаг перетаскивания, очистите холст и нарисуйте изображение в позиции мыши

Вот какой код:

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){


    var img = new Image();
    img.onload = function(){
        ctx.drawImage(img, 0,0);
    };
    img.src = "http://images.christmastimeclipart.com/images/2/1271716593176_1788/img_1271716593176_17881.jpg";

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var canvasOffset=$("#canvas").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;
    var canvasWidth=canvas.width;
    var canvasHeight=canvas.height;
    var isDragging=false;

    function handleMouseDown(e){
      canMouseX=parseInt(e.clientX-offsetX);
      canMouseY=parseInt(e.clientY-offsetY);
      // set the drag flag
      isDragging=true;
    }

    function handleMouseUp(e){
      canMouseX=parseInt(e.clientX-offsetX);
      canMouseY=parseInt(e.clientY-offsetY);
      // clear the drag flag
      isDragging=false;
    }

    function handleMouseOut(e){
      canMouseX=parseInt(e.clientX-offsetX);
      canMouseY=parseInt(e.clientY-offsetY);
      // user has left the canvas, so clear the drag flag
      //isDragging=false;
    }

    function handleMouseMove(e){
      canMouseX=parseInt(e.clientX-offsetX);
      canMouseY=parseInt(e.clientY-offsetY);
      // if the drag flag is set, clear the canvas and draw the image
      if(isDragging){
          ctx.clearRect(0,0,canvasWidth,canvasHeight);
          ctx.drawImage(img,canMouseX-128/2,canMouseY-120/2,128,120);
      }
    }

    $("#canvas").mousedown(function(e){handleMouseDown(e);});
    $("#canvas").mousemove(function(e){handleMouseMove(e);});
    $("#canvas").mouseup(function(e){handleMouseUp(e);});
    $("#canvas").mouseout(function(e){handleMouseOut(e);});

}); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=400 height=300></canvas>
</body>
</html>

Ответ 2

ответ markE дал мне большую часть пути, но у меня были некоторые проблемы с этим, узнав местоположение, в котором находилась моя мышь. Я прикрепляю свой код, хотя с тех пор Я работаю с OO JS, он будет по-разному структурирован:

    hitImage: function() {
      return (this.startX > this.imageX && this.startX < this.imageX + this.imageWidth && this.startY > this.imageY && this.startY < this.imageY + this.imageHeight);
    },

    handleMouseDown: function(e){
      this.startX = parseInt(e.clientX - this.offsetX);
      this.startY = parseInt(e.clientY - this.offsetY);
      // set the drag flag
      this.isDragging= this.hitImage;
    },

    handleMouseUp: function(e,img){
      this.startX=parseInt(e.clientX-this.offsetX);
      this.startY=parseInt(e.clientY-this.offsetY);
      // clear the drag flag
      this.isDragging=false;
      this.drawImage(e,img);
    },

    handleMouseOut: function(e,img){
      this.handleMouseUp(e,img);
    },

    handleMouseMove: function(e,img){
      // only compute new positions if in drag
      if(this.isDragging){

        this.canMouseX=parseInt(e.clientX - this.offsetX);
        this.canMouseY=parseInt(e.clientY - this.offsetY);
      // move the image by the amount of the latest drag
        var dx = this.canMouseX - this.startX;
        var dy = this.canMouseY - this.startY;

        this.imageX += dx;
        this.imageY += dy;
        // Negative image locations break the pattern in this.fillPattern
        this.imageY = Math.max(0, this.imageY);
        this.imageX = Math.max(0, this.imageX);

        // reset the startXY for next time
        this.startX = this.canMouseX;
        this.startY = this.canMouseY;

        this.drawImage(e,img);
      }