JSFiddle - React, Tailwind, and code Playground
HTML
<!-- Import @tensorflow/tfjs-core -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-core"></script>
<!-- Adds the WebGL backend to the global backend registry -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-webgl"></script>
<canvas width=500 height=500 id="mycanvas">
</canvas>
JavaScript
(async ()=>{
var rand = tf.randomUniform([500, 500]);
rand = tf.mul(rand,tf.scalar(2))
rand = tf.cast(rand, 'int32');
rand = tf.cast(rand, 'bool');
//rand.print();
rand = tf.expandDims(rand,2);
//rand.print();
var kernel = tf.tensor([[1,1,1],[1,8,1],[1,1,1]], [3,3], 'int32');
kernel = tf.expandDims(kernel,2);
kernel = tf.expandDims(kernel,3);
//kernel.print();
const new_state = tf.variable(rand);
for(var i = 0; i < 10000; i++){
tf.tidy(() => {
var convd = tf.conv2d (new_state, kernel, 1, 'same');
//convd.print();
/*
Any live cell with fewer than two live neighbours dies, as if by underpopulation.
Any live cell with two or three live neighbours lives on to the next generation.
Any live cell with more than three live neighbours dies, as if by overpopulation.
Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
<2 : 0
2-3 : 1
> 3: 0
dead:
1 neigbhor -> 1 (0)
2 neighbor -> 2 (0)
3 neighbor -> 3 (1)
4 neighbor -> 4 (0)
live (current counts as 8):
1 neigbhor -> 9 (0)
2 neighbor -> 10 (1)
3 neighbor -> 11 (1)
4 neighbor -> 12 (0)
*/
var is_3 = tf.equal(convd,tf.scalar(3,'int32'));
var is_10 = tf.equal(convd,tf.scalar(10,'int32'));
var is_11 = tf.equal(convd,tf.scalar(11,'int32'));
new_state.assign(tf.logicalOr (is_3, tf.logicalOr (is_10, is_11) ));
//new_state.print()
return null;
});
//var display = tf.mul(tf.cast(convd, 'int32'),tf.scalar(15,'int32'));
var display = tf.tidy(() => { return tf.mul(tf.cast(new_state, 'int32'),tf.scalar(255,'int32'))});
await tf.browser.toPixels (display, document.getElementById('mycanvas'));
//console.log(tf.getBackend())
//break;
}
})();