JSFiddle - React, Tailwind, and code Playground
by loktar
HTML
<body>
<button hidden>Prepare Image</button>
<canvas id="canvas"></canvas>
<h3>Click anywhere on the canvas to stop animation and select image</h3>
<img src="" id="canvasImg"></img>
</body>
CSS
button, h3 {
position: absolute;
top: 430px;
font-size: 1.3em;
padding: 7px;
}
h3 {
font-size: 1.7em;
top: 460px;
font-family: calibri;
color: teal;
}
#canvasImg, canvas {
position: absolute;
left: 10;
top: 10;
border: 5px solid tomato;
}
JavaScript
var canvas = document.getElementById('canvas');
function randomize(num) {
var a = Math.floor(Math.random() * num);
return a;
}
function sides() {
var a = Math.floor(Math.random() * 10);
return a;
}
function getRndColor() {
var r = 255 * Math.random() | 0,
g = 255 * Math.random() | 0,
b = 255 * Math.random() | 0,
alpha = 0.1; //Math.random().toFixed(1);
var final = 'rgba(' + r + ',' + g + ',' + b + ',' + alpha + ')';
return final;
}
$('*').click(function () {
clearInterval(timer);
$('button').show();
});
$('button').click(function () {
$(this).css('left', '-400px');
$('h3').text("Right click and save a beautiful background!");
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var dataURL = canvas.toDataURL();
ctx.clearRect(0, 0, canvas.width, canvas.height);
document.getElementById('canvasImg').src = dataURL;
$('#canvasImg').css('border', '5px solid black');
$('#canvas').hide();
$('#canvasImg').show();
});
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
var left = true;
canvas.width = 700;
canvas.height = 396;
var timer = setInterval(function () {
for (var i = 1; i <= 1000; i++) {
ctx.beginPath();
if (left) {
ctx.moveTo(0, randomize(canvas.height));
left = false;
} else {
ctx.moveTo(randomize(canvas.width), 0);
left = true;
}
ctx.lineTo(randomize(canvas.width), randomize(canvas.height));
ctx.lineTo(randomize(canvas.width), randomize(canvas.height));
ctx.fillStyle = getRndColor();
ctx.fill();
}
}, 1000);
}