JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://www.html5canvastutorials.com/libraries/kinetic-v3.5.2.js"></script>
<p id="msg">Messages...</p>
<div id="container">
</div>
CSS
canvas
{
margin:5px;
border:1px solid black;
}
JavaScript
function writeMessage(stage, message) {
$("#msg").html(message);
return;
var context = stage.getContext();
stage.clear();
context.font = "18pt Calibri";
context.fillStyle = "black";
context.fillText(message, 10, 25);
drawGrid(context);
}
var sideLen = 50;
var stage = new Kinetic.Stage("container", 250, 250);
var canvas = stage.getCanvas();
var box = new Kinetic.Shape(function() {
var context = this.getContext();
context.beginPath();
context.rect(0, 0, sideLen, sideLen);
context.lineWidth = 1;
context.strokeStyle = "black";
context.fillStyle = "#00D2FF";
context.fill();
context.stroke();
context.closePath();
});
// enable drag and drop
box.draggable(true);
// write out drag and drop events
box.on("dragstart", function() {
writeMessage(stage, "dragstart");
});
box.on("dragend", function() {
var point = box.getPosition();
var newX = Math.round( point.x / sideLen) * sideLen;
var newY = Math.round( point.y / sideLen) * sideLen;
writeMessage(stage, point.x + ", " + point.y + " -> " + newX + ", " + newY);
// broke...
// box.x = newX;
// box.y = newY;
// also broke...
// box.setPosition( newX, newY);
// and this one...
// box.setPosition( { x:newX, y:newY } );
});
stage.add(box);
drawGrid(stage.getContext());
function drawGrid(context){
// vertical
for( i=sideLen; i<250; i+=sideLen ){
context.moveTo(i, 0);
context.lineTo(i, 250);
context.stroke();
}
// horizontal
for( j=sideLen; j<250; j+=sideLen ){
context.moveTo(0, j);
context.lineTo(250, j);
context.stroke();
}
}