0

How can I clear the canvas when I click a button

I tried:

cx.fillRect()

but: it did not work for me and I just need to reload the canvas and not the page.

Here is my code:

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 is the screen when I run the code and click on the button :

here

Pineda
  • 7,435
  • 3
  • 30
  • 45
mafallahi
  • 1
  • 3

1 Answers1

0

You can try:

cx.clearRect(0, 0, 300, 600)

Pineda
  • 7,435
  • 3
  • 30
  • 45
  • 1
    Usually you should post a explanation with your code on how it works. This helps newer developers understand what you are doing. – Caleb Kleveter Jan 03 '17 at 16:24