JSFiddle - React, Tailwind, and code Playground
HTML
<head>
<script src="http://www.html5canvastutorials.com/libraries/kinetic-v4.3.0-beta2.js"></script>
</head>
<body>
<!-- Here we can give each button an id that
represents where it belongs. The first number is the
column and the second number is the row.
For example 0_0 would be upper left, 0_1 would be
lower left -->
<button id="0_0" class="buttons">Square 1</button>
<button id="1_0" class="buttons">Square 2</button>
<button id="0_1" class="buttons">Square 3</button>
<button id="1_1" class="buttons">Square 4</button>
<div id="container" style="height: 500px; width: 500px"></div>
</body>
JavaScript
//define some Kinetic stuff like before
var stage = new Kinetic.Stage({
container: 'container',
width: 500,
height: 500
});
var layer = new Kinetic.Layer();
var circle = new Kinetic.circle({
x: 0,
y: 0,
radius: 7,
fill: 'red',
stroke: 'black',
strokeWidth: 3
});
layer.add(circle);
stage.add(layer);
//define the box size
var width = 100;
var height = 100;
var margin = 5;
//get an array containing all of the button elements
var buttons = document.getElementsByClassName("buttons");
//loop through the array
//for each button, add a property that will
//hold the box info and attach an event listener
for(var i=0; i<buttons.length; i++){
//get the x/y coordinate for the box based
//on the id
var rowcol = buttons[i].id.split("_");
//need parseInt because split returns a string
var row = parseInt(rowcol[0]);
var col = parseInt(rowcol[1]);
//create the Kinetic shape and
//add it to the element as an object
//property called "box"
buttons[i].box = new Kinetic.Shape({
drawFunc: function(canvas) {
var ctx = canvas.getContext();
ctx.beginPath();
//The basic here idea is to multiple row and column numbers
//by the total width (or height) of a box then add an offset
//margin for each corner
ctx.moveTo( //upper left
(this.row * width) + margin,
(this.col * height) + margin
);
ctx.lineTo( //upper right
((this.row + 1) * width) + margin,
(this.col * height) + margin
);
ctx.lineTo( //lower right
((this.row + 1) * width) + margin,
((this.col + 1) * height) + margin
);
ctx.lineTo( //lower left
(this.row * width) + margin,
((this.col + 1) * height) + margin
);
ctx.closePath();
canvas.fillStroke(this);
},
fill: '#c5d0fc',
stroke: '#0032ff',
strokeWidth: 4,
opacity: 0
});
//attach the row and column index to the shape...