JSFiddle - React, Tailwind, and code Playground
by projeqht
HTML
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.4.3.min.js"></script>
<p>Draw rectangles with your mouse</p>
<button id="rect">Rect</button>
<button id="undo">Undo</button>
<button id="redo">Redo</button>
<div id="container"></div>
CSS
#container{
border:solid 1px #000;
margin:10px;
width:400px;
height:400px;
}
JavaScript
//http://stackoverflow.com/questions/16096875/how-to-create-undo-redo-in-kineticjs/16302533#16302533
//Init
history = new Array();
historyStep = -1;
//KineticJS Stage/Canvas Setup
layer = new Kinetic.Layer();
stage = new Kinetic.Stage({
container: "container",
width: 400,
height: 400
});
background = new Kinetic.Rect({
x: 0,
y: 0,
width: stage.getWidth(),
height: stage.getHeight()
});
layer.add(background);
stage.add(layer);
makeHistory();
//Draw Rectangle with Mouse
function drawRect() {
var rect, down = false,oPoint;
layer.on("mousedown.rect", function(e) {
down = true;
oPoint = originalPoint = {x:e.layerX, y:e.layerY};
rect = new Kinetic.Rect({
x: e.layerX,
y: e.layerY,
width: 0,
height: 0,
fill: '#FFF',
stroke: '#000'
});
layer.add(rect);
});
layer.on("mousemove.rect", function(e) {
if (!down) return;
var p = rect.attrs,
w = e.layerX - p.x,
h = e.layerY - p.y;
rect.setX(oPoint.x);
rect.setY(oPoint.y);
rect.setWidth(w);
rect.setHeight(h);
layer.draw();
});
layer.on("mouseup.rect", function(e) {
down = false;
if(rect.attrs.width===0 && rect.attrs.height===0){
console.debug('removed');
rect.remove();
layer.draw();
}
makeHistory();
});
}
//Undo Redo Functions
function makeHistory() {
historyStep++;
if (historyStep < history.length) {
history.length = historyStep;
}
json = layer.toJSON();
history.push(json);
}
function undoHistory() {
if (historyStep > 0) {
historyStep--;
layer.destroy();
layer = Kinetic.Node.create(history[historyStep], 'container')
stage.add(layer);
}
drawRect();
}
function redoHistory() {
if...