JSFiddle - React, Tailwind, and code Playground

by Jake Doe

HTML

drag the image
<canvas id="c" width = "500" height = "500" ></canvas>

JavaScript

var canvas = $("#c");
var c = canvas[0].getContext("2d");

var path = "https://i.imgur.com/TbsC8vP.jpg";
var image1 = new DragImage(path, 200, 100);
var image2 = new DragImage(path, 300, 100);

var loop = setInterval(function() {

    c.fillStyle = "gray";
    c.fillRect(0, 0, 500, 500);

    image1.update();
    image2.update();
}, 30);

var mouseX = 0,
    mouseY = 0;
var mousePressed = false;
var dragging = false;
canvas.mousemove(function(e) {
    mouseX = e.offsetX;
    mouseY = e.offsetY;
})

$(document).mousedown(function() {
    mousePressed = true;
}).mouseup(function() {
    mousePressed = false;
    dragging = false;
});

function DragImage(src, x, y) {
    var that = this;
    var startX = 0,
        startY = 0;
    var drag = false;
    
    this.x = x;
    this.y = y;
    var img = new Image();
    img.src = src;
    this.update = function() {
        if (mousePressed ) {
            
                var left = that.x;
                var right = that.x + img.width;
                var top = that.y;
                var bottom = that.y + img.height;
                if (!drag) {
                    startX = mouseX - that.x;
                    startY = mouseY - that.y;
                }
                if (mouseX < right && mouseX > left && mouseY < bottom && mouseY > top) {
                    if (!dragging){
            dragging = true;
                        drag = true;
                    }
                    
                }
            
        } else {
             
            drag = false;
        }
        if (drag) {
            that.x = mouseX - startX;
            that.y = mouseY - startY;
        }
        c.drawImage(img, that.x, that.y);
    }
}