The canvas animation displays a sequence of previous frames

My challenge lies in rotating an object on the canvas, as all previous frames continue to be displayed. I suspect the issue is related to this particular line of code:

setTimeout(this.rotate.bind(this), 1000 / 10);

Is there a way to have only the current frame shown?

(function () {
    var spinner = {
        playerx: 810 * 0.5,
        playery: 600 * 0.75,
        shield: 1.80,
        rotation: 0,
        polyxx: [0, 12, 12, 0, -12, -12],
        polyyy: [-13.92, -5.35, 5.35, 13.92, 5.35, -5.35],
        size: 5,

        canvasInit: function () {
            this.canvas = document.getElementById('loadingScreen');
            this.ctx = this.canvas.getContext('2d');
        },

        rotate: function () {

            this.rotation += 0.02;
            this.shield -= 0.01;
            this.ctx.strokeStyle = 'rgba(255,255,255,' + this.shield + ')';

            this.ctx.save();
            this.ctx.translate(this.playerx, this.playery - 10);
            this.ctx.rotate(this.rotation);
            this.ctx.translate(-this.playerx, -(this.playery - 10));
            this.ctx.beginPath();
            this.ctx.lineWidth = 17;
            for (var a = 0; a < 6; a++) {
                this.ctx.lineTo(this.playerx + this.polyxx[a] * this.size, this.playery - 10 + this.polyyy[a] * this.size);
            }

            this.ctx.closePath();
            this.ctx.stroke();
            this.ctx.restore();


            this.loop();

        },

        loop: function () {
            setTimeout(this.rotate.bind(this), 1000 / 10);
        },

        init: function () {
            this.canvasInit();
            this.loop();
        }
    };
    spinner.init();
})();
<body>
    <canvas style="background:#000;" id="loadingScreen" width="810" height="600"></canvas>
</body>

Answer №1

Make sure to clear the canvas every time you animate.

Include

this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
at the start of your rotate function to accomplish this.

Here is an example:

(function () {
    var spinner = {
        playerx: 810 * 0.5,
        playery: 600 * 0.75,
        shield: 1.80,
        rotation: 0,
        polyxx: [0, 12, 12, 0, -12, -12],
        polyyy: [-13.92, -5.35, 5.35, 13.92, 5.35, -5.35],
        size: 5,

        canvasInit: function () {
            this.canvas = document.getElementById('loadingScreen');
            this.ctx = this.canvas.getContext('2d');
        },

        rotate: function () {
            // Clearing the canvas here ensures a clean frame for drawing
            this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

            this.rotation += 0.02;
            this.shield -= 0.01;
            this.ctx.strokeStyle = 'rgba(255,255,255,' + this.shield + ')';

            this.ctx.save();
            this.ctx.translate(this.playerx, this.playery - 10);
            this.ctx.rotate(this.rotation);
            this.ctx.translate(-this.playerx, -(this.playery - 10));
            this.ctx.beginPath();
            this.ctx.lineWidth = 17;
            for (var a = 0; a < 6; a++) {
                this.ctx.lineTo(this.playerx + this.polyxx[a] * this.size, this.playery - 10 + this.polyyy[a] * this.size);
            }

            this.ctx.closePath();
            this.ctx.stroke();
            this.ctx.restore();

            this.loop();

        },

        loop: function () {
            setTimeout(this.rotate.bind(this), 1000 / 10);
        },

        init: function () {
            this.canvasInit();
            this.loop();
        }
    };
    spinner.init();
})();
<body>
    <canvas style="background:#000;" id="loadingScreen" width="810" height="600"></canvas>
</body>

Important Note:

You might also want to consider using requestAnimationFrame instead of setTimeout for better animation performance.

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

Node Js is a lightweight server that allows for easy querying of URLs

I've been exploring various examples but I'm still struggling to understand how it all functions. My goal is quite simple, or so I thought. I was hoping someone could assist me? The task at hand is to establish a server for clients to connect t ...

How can we manage a discovered item in Promise and Recursion scenarios without relying on a callback function?

I need to iterate asynchronously and recursively over a folder hierarchy on the server. When a file is found, I want to call a custom method. Here's my current code structure: searchFile(root, handleFile); // recursively loop through folders and ha ...

Pick the item when the checkbox is selected

I am currently attempting to toggle the visibility of a select element based on whether a checkbox is checked or not, but it doesn't seem to be working as expected. My desired functionality is for the select element to be hidden upon page load and th ...

"Utilizing the splice method to insert an element at specified indexes within an

const list = [] const obj = { name: '', mobile: '' } _.forEach(errors, (value, key) => { // eslint-disable-next-line no-debugger // debugger const field = key. ...

Updating a boolean value from true to false within a Vue component while making an Axios API request

My Vue.js and Axios setup involves making an API call, where I aim to temporarily change the value of a variable from false to true using SetTimeout. However, there seems to be an issue with Vue not responding unless the variable name is hard coded. Withi ...

Tips for reorganizing the JSON data created by Artoo.js?

My file aims to scrape data from a single webpage, but I've hit a roadblock. I initially tried using artoo, request, and cheerio based on my research. Here's the code I have so far: request('http://www.ciclopi.eu/frmLeStazioni.aspx?ID=144&a ...

Is it possible to establish a scope for jquery.ajaxSetup()?

Currently, I am working on a project involving numerous ajax calls with repetitive parameters. After some consideration, I am contemplating using jquery.ajaxSetup() to streamline the code. However, jQuery does not recommend this approach in their API docu ...

Loading `.obj` and `.mtl` files in THREE.js with accompanying PNG textures

I am facing an issue while attempting to load an mtl file with reference to png textures for my obj model. The error I am encountering is as follows: TypeError: manager.getHandler is not a function Below is the snippet of my three.js code: var loadOBJ = ...

Securing Email and Password Data in Cypress Tests

Greetings! I trust everyone is in good spirits. My dilemma lies in the fact that I am hesitant to include email and passwords in version control. I am considering using environment variables in my cypress tests and utilizing secrets for runtime value pro ...

Adjusting the height of the search icon through the Jquery toggle action to create animated effects

While trying to create a search field with the click function (animate), I noticed an issue similar to what is seen in this example: . Whenever the search icon is clicked, it moves up and down unexpectedly, and I am uncertain as to why this behavior is occ ...

Angular date selection with a range of plus two days, factoring in the exclusion of weekends

I am currently using a mat date picker range with specific logic. The minimum date that a user can select on the calendar is set to + 2 days. For example, if today's date is July 20, 2022, the minimum selectable date would be July 22, 2022. However, ...

What is the best way to include text in an editor access notification email?

I've developed a script to assign editors to a spreadsheet, but I'm looking to personalize the emails sent to them. The screenshot below illustrates the step where I can input a message for the email recipients who have been granted access. f ...

Comparison of jQuery, AngularJS, and Node.js

I'm a beginner in web development and I have some basic knowledge: HTML - structure of websites CSS - design aspect JavaScript - for adding interactivity Now, what exactly is jQuery, AngularJS, and Node.js? Upon researching, I discovered that jQue ...

Effective methods for importing components in VueJS 2.0

As a newcomer to VueJs, I have a question regarding the best practice for importing components in a Vue Template Project. I currently have some components that are used in multiple views. After downloading an admin template, I noticed that the samples alwa ...

Remove an element from an array based on the index provided by the front end

Currently, I am attempting to eliminate a specific item from a PHP array stored in a JSON file. Here is an example of the JSON file structure: { "1.49514754373E+12": { "description": "I don't like it", "fileNames": [ " ...

What are Fabric.js tools for "Drop Zones"?

Has anyone successfully created a "drop zone" similar to interact.js using fabric.js? I haven't had the chance to experiment with it myself. I have some ideas on how I could potentially implement it, but before diving in, I wanted to see if anyone el ...

Using JavaScript to pass a newly created variable as an argument in a default

Currently, I am developing a node application that heavily utilizes promises. To enhance the readability of my code, I have been removing anonymous functions and storing them in a JavaScript object called "myCallbacks". Here's an example: let myCallb ...

Tips for sending parameters in onClick within a React Functional Component

In my ReactJS Functional Component, I need to pass a few values when a button is clicked. The code snippet for this functionality is below: <span className="edit" onClick={ onClickEdit(value.title, value.details)}> <img src={editImg} height=" ...

jinja2.exceptions.TemplateSyntaxError: instead of 'static', a ',' was expected

My current project involves using Flask for Python, and I encountered an error when running the project from PyCharm. The error message points to line 192 in my home.html file: jinja2.exceptions.TemplateSyntaxError: expected token ',', got &ap ...

Comparison of Grant and Passport.js: Which One to Choose?

Are you unsure about the distinctions between Grant and Passport.js? How do you decide when to utilize Grant over passport.js, and vice versa? If your goal is to create a social media platform that tracks user activities and posts them on a news feed, whi ...