Is there a way to reset the canvas with just a click of a button?

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:

here

Answer №1

One possible solution is:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve both the key and corresponding value from a JSON object

I am attempting to extract the key and value pairs from a JSON dataset. $.get(url, function (data) { console.log(data); if (data.Body != null) { console.log(data.Body); } }); These are my current logs: { $id: "1", Exceptions ...

The Reason Behind Component Non-ReRendering in Redux

I am currently facing an issue with my component and reducer. The `componentDidMount()` method in my component is calling a server to get some data, but the component doesn't re-render after the action is performed. I have checked my code multiple tim ...

How can we eliminate duplicate arrays of objects within a multi-dimensional array using ReactJS and JavaScript?

let galleryItems = [ {id: 1029, name: 'College-Annual-Day.jpg', ext: 'jpg', mime: 'image/jpeg', size: 91153, …}, {id: 1029, name: 'College-Annual-Day.jpg', ext: 'jpg', mime: 'image/jpeg', si ...

Cookies are failing to be saved upon reloading the page

I found this snippet of code $(document).ready(function () { var d = new Date(); var newMinutes = d.getTimezoneOffset(); var storedMinutes = getCookieValue("tzom"); if (newMinutes != storedMinutes) { setCookie("tzom", newMinutes) ...

What is the proper way to utilize a variable within the translate3d function?

Currently, I am developing my portfolio and working on a function in JavaScript called translate3d(0,10px,0). My question is, how can I use a variable instead of hardcoding the value 10px? I attempted to use translate3d(0,a,0) where 'a' is a vari ...

Automatically populating username and password fields

Is it possible to set up automatic username and password filling on my website for users who have saved their login information in their browser? I want the user to just hit enter to login. Some websites already have this feature enabled, but others requi ...

Is it considered safe to display the error message from an AJAX call for security reasons?

When I make my ajax calls, they usually follow this pattern: $.ajax({ type: 'POST', url: '/Controller/DoSomethingSpecial', contentType: 'application/json;', ...

What is the best way to fetch all the orders from my product schema using response.send?

This is my custom Product schema const productSchema = new mongoose.Schema({ title: { type: String, required: [true, "Title is required"] }, details: { type: String, required: [true, "Details are r ...

Creating a custom function in JavaScript to interact with the `windows.external` object specifically for use

In my current project, I am facing an issue with JavaScript file compatibility across different browsers. Specifically, I have a JavaScript file that calls an external function (from a separate file) using windows.external, like this: windows.external.se ...

Swapping out data within a container

I've been experimenting with creating a hangman game using JavaScript and HTML. However, I'm facing an issue where clicking on a letter doesn't replace the "_" placeholder. var myList=["Computer","Algorithm","Software","Programming","Develop ...

Transfer information to an ExpressJS server in order to display a fresh view

I'm struggling to figure out how to transfer data from the client side to an ExpressJS server in order to generate a view based on that information. When users choose different parameters on the client side, they update the 'data-preference&apos ...

The issue with fancybox links not functioning properly within ajax content

I'm looking to constantly update a specific section on my website using ajax, jquery, and php. Upon the initial page load, a javascript function is triggered to display the content of that section. Subsequently, json is utilized to check for any new ...

Utilizing External Libraries Added Through <script> Tags in React

My goal is to develop a Facebook Instant HTML5 application in React. Following their Quick Start guide, Facebook requires the installation of their SDK using a script tag: <script src="https://connect.facebook.net/en_US/fbinstant.6.3.js"></scrip ...

exploring div element(s) with jQuery

My HTML page contains multiple div elements in the body. I have also included buttons with associated click functions in jQuery to change the background-color of a div element based on the button pressed. However, I'm facing an issue at the 'term ...

GraphQL failing to communicate with WP API

Any help is appreciated! I am currently retrieving data from a WP Rest API. When I run the WordPress site locally on my machine using http://localhost:8000 and access the graphql playground at http://localhost:3000/api/graphql, everything works fine as ex ...

What methods can be utilized to conceal an if statement in code?

In my application, I am facing an issue with an external JavaScript file that contains multiple if statements. The problem arises when one of the if statements is still being executed even if the corresponding form is hidden. The flow of my application is ...

Collaborating and monitoring data between controllers

A unique challenge has arisen as we implement a tree-style navigation element that must communicate with other directives/controllers. The main objectives are: Keep track of the current selection, Detect when the row selection changes. The task at hand ...

Using VueJS to apply filters to an object causes a decrease in my application's performance

Recently, I've been working on implementing a filter for a search bar. However, I've noticed that whenever I input something into the search bar, there is a noticeable delay as it loads the entries. I'm not sure if this issue is related to ...

Issue with triggering blur event in Internet Explorer while using Angular 2+

The issue discussed in the Blur not working - Angular 2 thread is relevant here. I have a custom select shared component and I am attempting to implement a blur event to close it when the component loses focus. // HTML <div (blur)="closeDropDown()" t ...

Definition in Typescript: The term "value is" refers to a function that takes in any number of arguments of

export function isFunction(value: any): value is (...args: any[]) => any { return typeof value === 'function'; } What is the reason behind using value is (...args: any[]) => any instead of boolean ? ...