JSFiddle - React, Tailwind, and code Playground

by m1erickson

HTML

<h4>Drag from the blue toolbar to the red canvas</h4>
<div id="toolbar">
    <img class="tool" width=32 height=32 src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-1.jpg">
    <img class="tool" width=32 height=32 src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-2.jpg">
    <img class="tool" width=32 height=32 src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-3.jpg">
    <img class="tool" width=32 height=32 src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-4.jpg">
</div>
<br>
<canvas id="canvas" width=350 height=300></canvas>

CSS

body{ background-color: ivory; }
canvas{border:1px solid red;}
#toolbar{
    width:350px;
    height:35px;
    border:solid 1px blue;
}

JavaScript

// get references to the canvas and its context
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

// get the offset position of the kinetic container
var $canvas = $("#canvas");
var Offset = $canvas.offset();
var offsetX = Offset.left;
var offsetY = Offset.top;


// select all .tool's
var $tools = $(".tool");


// make all .tool's draggable
$tools.draggable({
    helper: 'clone',
});


// assign each .tool its index in $tools
$tools.each(function (index, element) {
    $(this).data("toolsIndex", index);
});


// make the canvas a dropzone
$canvas.droppable({
    drop: dragDrop,
});


// handle a drop into the canvas
function dragDrop(e, ui) {

    // get the drop point (be sure to adjust for border)
    var x = parseInt(ui.offset.left - offsetX) - 1;
    var y = parseInt(ui.offset.top - offsetY);

    // get the drop payload (here the payload is the $tools index)
    var theIndex = ui.draggable.data("toolsIndex");

    // drawImage at the drop point using the dropped image 
    ctx.drawImage($tools[theIndex], x, y, 32, 32);

}