JSFiddle - React, Tailwind, and code Playground
by vrmtm
HTML
<html>
<head>
<title>layeredCanvas Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<style>
body {
background: white;
}
.column {
width: 50%;
float:left;
}
.clear { clear:both; }
</style>
</head>
<body>
<div>
<div class="column">
<canvas id="theCanvas" width="512" height="512"></canvas>
<div>
<label><input type="checkbox" id="squares" checked >Squares</label>
<label><input type="checkbox" id="circles" checked >Circles</label>
<label><input type="checkbox" id="triangles" checked >Triangles</label>
</div>
</div>
<div class="column">
<pre>
</pre>
</div>
<div class="clear"></div>
</div>
</body>
</html>
JavaScript
layeredCanvas = function ( id ) {
this.layers = [];
var extend = function ( defaults, options ) {
var extended = {} , prop;
for (prop in defaults) {
if (Object.prototype.hasOwnProperty.call(defaults, prop))
extended[prop] = defaults[prop];
}
for (prop in options) {
if (Object.prototype.hasOwnProperty.call(options, prop))
extended[prop] = options[prop];
}
return extended;
};
this.addLayer = function( obj ) {
layer = extend( {
id: Math.random().toString(36).substr(2, 5),
show: true,
render: function( canvas, ctx ) {}
}, obj );
if ( this.getLayer( layer.id ) !== false ) {
console.log( 'Layer already exists' );
console.log( obj );
return false;
}
this.layers.push( layer );
return this;
};
this.getLayer = function( id ) {
var length = this.layers.length;
for ( var i = 0; i < length; i++ ) {
if ( this.layers[i].id === id )
return this.layers[i];
}
return false;
};
this.removeLayer = function( id ) {
var length = this.layers.length;
for ( var i = 0; i < length; i++ ) {
if ( this.layers[i].id === id ) {
removed = this.layers[i];
this.layers.splice( i, 1 );
return removed;
}
}
return false;
};
this.render = function() {
var canvas = this.canvas;
var ctx = this.ctx2d;
this.layers.forEach( function( item, index, array ) {
if ( item.show )
item.render( canvas, ctx );
});
};
this.canvas = document.getElementById( id );
this.ctx2d = this.canvas.getContext( '2d' );
};
var myCanvas = new layeredCanvas( "theCanvas" );
myCanvas.addLayer( {
id: 'background',
render: function( canvas, ctx ) {
ctx.fillStyle = "black";
ctx.fillRect( 0, 0, canvas.width, canvas.height );
}
})
.addLayer( {
id: 'squares',
render: function( canvas, ctx ) {
ctx.fillStyle = "#E5E059";
ctx.fillRect( 50, 50, 150, 150 );
ctx.fillStyle = "#BDD358";
ctx.fillRect( 350, 75, 150, 150 );
ctx.fillStyle = "#E5625E";
ctx.fillRect( 50,...