JSFiddle - React, Tailwind, and code Playground
by Programmer
HTML
<script src="http://www.html5canvastutorials.com/libraries/kinetic-v3.5.2.js"></script>
<p id="msg">Messages...</p>
<div id="container">
</div>
CSS
p
{
padding : 5px;
}
canvas
{
margin-left : 5px;
border : 1px solid black;
cursor : pointer;
}
JavaScript
var gridResolution = 5;
var sideLen = 50;
var width = sideLen * gridResolution;
var height = sideLen * gridResolution;
var stage = new Kinetic.Stage("container", width, height);
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() {
});
box.on("dragend", function() {
var point = box.getPosition();
var newX = Math.round(point.x / sideLen) * sideLen;
var newY = Math.round(point.y / sideLen) * sideLen;
$("#msg").html(point.x + ", " + point.y + " -> " + newX + ", " + newY);
var context = stage.getContext();
stage.clear();
box.setPosition(newX, newY);
drawGrid(context);
stage.draw();
});
stage.add(box);
drawGrid(stage.getContext());
function drawGrid(context) {
// vertical
for (i = sideLen; i < width; i += sideLen) {
context.moveTo(i, 0);
context.lineTo(i, width);
context.stroke();
}
// horizontal
for (j = sideLen; j < height; j += sideLen) {
context.moveTo(0, j);
context.lineTo(height, j);
context.stroke();
}
}