How do I reset the canvas upon button click?
I attempted:
cx.fillRect()
However, the above method did not work as expected. I simply want to refresh the canvas without reloading the entire page.
Below is my current code snippet:
var canvas = document.getElementById('canvas');
var cx = canvas.getContext('2d');
canvas.height = 300;
canvas.width = 600;
function branch(length, angle, scale) {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
cx.fillStyle = 'rgb(' + r + ',' + g + ',' + b + ')';
cx.fill();
cx.fillRect(0, 0, 1, length);
if (length < 8) return;
cx.save();
cx.translate(0, length);
cx.rotate(-angle);
branch(length * scale, angle, scale);
cx.rotate(2 * angle);
branch(length * scale, angle, scale);
cx.restore();
}
cx.translate(300, 2);
function change() {
a = Math.random();
branch(60, a, 0.8);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8>
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
canvas{
margin: 100px auto;
position: absolute;
left: 0;right: 0;
top: 0;bottom: 0;
border: 1px solid #ccc;
background-color: #ECEFF1;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<button onclick="change()">Change</button>
<script src="main.js"></script>
</body>
</html>
This image illustrates the result when the code is executed and the button is clicked: