Creating recurring shapes in the Canvas element

I just joined this platform and I'm trying to create an animation using canvas. My goal is to redraw a circle every 2 seconds with a canvas reset in between. The circle should appear randomly within the canvas, which I was able to accomplish. However, I'm struggling to make the animation repeat itself every 2 seconds. I tried using the requestAnimationFrame callback, but it refreshes too quickly, around 60 times per second.

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

var requestAnimationFrame = window.requestAnimationFrame ||
                        window.mozRequestAnimationFrame ||
                        window.webkitRequestAnimationFrame ||
                        window.msRequestAnimationFrame;


function reset(){
    draw();
    requestAnimationFrame(reset);
}

function draw(){
    var X = Math.floor(Math.random()*canvas.width);
    var Y = Math.floor(Math.random()*canvas.height);
    var radius = 70;

    context.clearRect(0,0, canvas.width, canvas.height);
    context.beginPath();
    context.arc(X, Y, radius, 0, 2 * Math.PI, false);
    context.fillStyle = 'red';
    context.fill();
}

function main(){
    requestAnimationFrame(reset);
}

main();

I followed your advice and updated the code, now I see circles every two seconds, but the canvas is not resetting in between.

function main(){
    setInterval(function(){
        draw();
        context.clearRect(0,0, 640,480);
    },2000);
};

I believe I found a solution, or at least a way to approach it. I combined your suggestion with a setTimeout function.

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

function draw() {
    var X = Math.floor(Math.random() * canvas.width);
    var Y = Math.floor(Math.random() * canvas.height);
    var radius = 70;

    context.beginPath();
    context.arc(X, Y, radius, 0, 2 * Math.PI, false);
    context.fillStyle = 'red';
    context.fill();
}

function reset() {
    canvas.width = canvas.width;
}

function action() {
    draw();
    setTimeout(function() {
        reset()
    }, 2000);
}

function main() {
    setInterval(function() {
        action();
    }, 2200);
}

main();

Answer №1

To improve the performance of your animation, you can utilize the timestamp provided by the requestAnimationFrame method to limit the drawing to one frame per second.

By calculating the elapsed milliseconds between each draw based on the timestamp passed to your animation loop, you can determine when it's time to update the display. If less than 1000ms have passed since the last draw, no action is taken. However, if 1000ms or more have passed, the draw() function is executed and the startTime is reset to begin counting another 1000ms delay.

For a demonstration and sample code, check out this link: http://jsfiddle.net/m1erickson/mwuc0tby/

var startTime;
var interval = 1000;

requestAnimationFrame(animate);

function animate(t) {
    requestAnimationFrame(animate);
    if (!startTime) {startTime = t;}
    if (t - startTime < interval) {return;}
    startTime = t;
    draw();
}

Switching to requestAnimationFrame is recommended for its built-in optimizations that enhance resource utilization and overall performance.

Answer №2

A simple alternative is to utilize the setInterval method:

setInterval(function() {
  // perform circle drawing logic
  // reset any necessary variables
}, 2000);

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

Receiving a JavaScript function's output with Python Selenium

Currently, I am in the process of scraping data from a specific webpage. The focus is on extracting the return string value from a Javascript function snippet. The target value to be extracted is indicated as "2227885" https://i.sstatic.net/5dLJ ...

The timer does not stop running even after navigating to a different page

Currently, I am utilizing the yo:angular-fullstack generator for developing my website. After a user registers on the site, an activation email is sent containing a verification link. Upon clicking the link, a message confirming successful activation is di ...

Display information from dynamically generated pages using Gatsby JS sourcing data from CSV files

I've been working on creating pages in Gatsby JS from a csv file and everything seemed to be going smoothly. However, when it comes to displaying the data on these generated pages, I keep running into issues with undefined variables and can't see ...

What is the best way to locate a particular JSON key value pair through JavaScript?

I'm in the process of creating a unique app that forecasts the weather for an upcoming event based on the city location specified. To achieve this, I am utilizing two APIs - one API provides an array of objects representing each event by an artist ent ...

Utilize data fields beyond the export default in Vue

Is there a way to access the information stored within the export default in my Vue component's JavaScript file? Specifically, I am trying to retrieve the contents of the routes array within the calculateAndDisplayRoute() function. overview.js funct ...

JavaScript module encounters an uncaught error: Attempting to assign a value to a constant variable

In another module, I defined a variable in the following manner: // module1.js let directory; export { directory }; Now, I am trying to access it in a separate module like so: // module2.js import { directory } from '../js/module1.js'; directo ...

The unboundStoryFn function returned nothing from the render, indicating that a return statement is likely missing. To render nothing, simply return null

While trying to test a react search component using storybook, I encountered an error called unboundStoryFn. The error message indicates that unboundStoryFn(...): Nothing was returned from render. This usually means a return statement is missing. Or, to re ...

Getting started with imports in typescript package

Having trouble with imports in a TypeScript package. I have two classes, A and B, located in the models directory. Currently, I am importing class B into class A like this: import B from "models/B" interface A { b: B } export default A; H ...

Exploring the relationship between Javascript constructors and memory management

In my Durandal-based SPA, I am utilizing the constructor below. Despite reaching out to the Durandal google group for help, I have not received a response yet. It is worth noting that the Durandal framework handles the instantiation of this viewmodel when ...

Maintain original image file name when downloading

I have successfully created a download link containing a base 64 encoded image. The only issue is that I need to retain the original file name, which is dynamic and cannot be hardcoded. downloadImage: function(){ var image_url = document.getEleme ...

What could be the reason my dropdown menu is not appearing on hover?

Currently, I am in the process of developing a menu using angularJS and google app script within a dialog box. I have been referring to this sample code for guidance. Instead of pasting all my code here, I can summarize what I have come up with: var a ...

Tooltip not displaying value on Google Line Chart when hovered over

Utilizing the Google Line Charts within Angular2 and TypeScript, I encountered an issue. While the line chart appeared visually appealing, the tool-tip did not display the exact values when hovered over a point on the chart. I'm puzzled as to why the ...

Mouse over the image to reveal a fresh window

I'm attempting to achieve a similar effect to that of this website (you may need to register to view it). Here's the image that illustrates it: As you can observe, when I hover over the image, a box appears and then when I hover over the YouTube ...

Struggling to get a price calculator up and running efficiently

The code I have should be functioning, however, when I insert it into the code module in the Divi theme on WordPress, it doesn't work. Interestingly, when I try it in a notepad, it works perfectly fine but fails to function on the website itself. () ...

Implementing Knockout.js with JqueryUI Autocomplete: Access the complete object instead of just the value

I have implemented a custom binding for a JQueryUI auto complete feature that works well. However, I am looking to modify it so that it returns the Item object, which can then be pushed to another array. Can someone provide guidance on how to achieve this ...

Activate JavaScript validation

Within each section (displayed as tabs), I have a custom validator. When one tab is active, the other is hidden. To proceed to submission, I need to disable client validation for the inactive tab. I attempt to do this by calling ValidatorEnable(, false); ...

The sorting function in Vue.js, _.orderBy, seems to be having trouble sorting

UPDATE This is the json data retrieved through an API using axios. bannerData= [ { "id": 118, "title": "Geruchsbel\u00e4stigung", "location": "DOR", "pressInformation": [ { ...

Move the camera left and right, up and down using the arrow keys in WebGL

I am currently working on implementing a basic camera movement system in WebGL using JavaScript and the keyboard to control the camera's movement along the X and Y axes. However, I am facing an issue where the camera moves in world coordinates rather ...

Toggle the visibility of items based on the user's login status

Below is the code snippet for when the user is logged out: <div class="fusion-secondary-main-menu"> <div class="fusion-row"> <?php avada_main_menu(); ?> <?php avada_mobile_menu_search( ...

Neglect variables that have not been declared (TypeScript)

Currently, I am working on developing a WebExtension using TypeScript that will be later compiled into JavaScript. This extension relies on one of the browser APIs offered by Firefox, specifically the extension API. An example of this is my use of the get ...