JSFiddle - React, Tailwind, and code Playground
by tctruckscience
September 23, 2013
HTML
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.5.4.min.js"></script>
<p>Blue group will recenter after scaling</p>
<button id="wider">Wider</button>
<button id="narrower">Narrower</button>
<div id="container"></div>
CSS
body {
padding:15px;
}
#container {
border:solid 1px #ccc;
margin-top: 10px;
width:300px;
height:300px;
}
JavaScript
var stage = new Kinetic.Stage({
container: 'container',
width: 300,
height: 300
});
var layer = new Kinetic.Layer();
stage.add(layer);
// objects used in jquery events
var drawingGroup;
var rect, circle;
var stageWidth = stage.getWidth();
var stageHeight = stage.getHeight();
var rectWidth = 2600;
var pixelsPerScaleUnit = 280 / 2600;
var rectWidthScaled = rectWidth * pixelsPerScaleUnit;
drawingGroup = new Kinetic.Group({
x: 20,
y: stageHeight / 2 - 50,
width: rectWidthScaled,
height: 100,
});
drawingGroup.scaleBy = function (scaleChange) {
this.scaleFactor = scaleChange;
this.setScale(scaleChange);
layer.draw();
};
layer.add(drawingGroup);
var rect = new Kinetic.Rect({
x: 0,
y: 0,
width: 260,
height: 100,
stroke: "lightgray",
fill: "skyblue"
});
drawingGroup.add(rect);
var circle = new Kinetic.Circle({
x: 50,
y: 50,
radius: 20,
fill: "blue"
});
drawingGroup.add(circle);
var status = new Kinetic.Text({
x: 15,
y: 15,
text: "width=240, scale=1.00",
fontSize: 18,
fill: "red"
});
layer.add(status);
setStatus();
layer.draw();
function setStatus() {
var width = drawingGroup.getWidth();
var length = rectWidth;
var scale = Math.round(drawingGroup.scaleFactor * 100);
status.setText("Width: " + width + ", Scale: " + scale + "%" + ", Length: " + length);
}
// widen by 20px and scale down by 15%
$("#wider").click(function () {
originalRectWidth = 2600;
rectWidth = rectWidth + 20;
scaleValue = originalRectWidth / rectWidth;
oldRectWidth = rect.getWidth();
newPixelsPerScaleUnit = 260 / rectWidth;
newRectScaled = rectWidth * newPixelsPerScaleUnit;
drawingGroup.setWidth(newRectScaled);
rect.setWidth(newRectScaled);
drawingGroup.scaleBy(scaleValue);
setStatus();
layer.draw();
});
$("#narrower").click(function () {
originalRectWidth = 2600;
rectWidth = rectWidth - 20;
...