Tips for crafting a perpetually looping animated shape using canvas

Lately, I've been experimenting with canvas and have encountered a challenge that I can't seem to solve. I've mastered creating shapes, animating them, and looping them across the canvas. However, I'm struggling to figure out how to spawn another shape behind the first one after a specific amount of time. My goal is to create a grid of squares moving horizontally.

I thought about encapsulating the for loop along with the shape's code in a variable and then using setTimeout() to respawn the entire sequence after a set number of milliseconds, but I'm uncertain if that approach would be effective.


function draw(x,y) {
  // Get canvas element
  var canvas = document.getElementById('canvas');
  // Set up drawing context
  var ctx = canvas.getContext('2d');
  // Begin drawing
  ctx.save();
  ctx.clearRect(0, 0, 550, 400);

  for(var i = 0 ; i < 400 ; i+=10){
    ctx.fillStyle = "rgb(0, 200, 0)";
    ctx.fillRect(x, i, 5, 4);
  }

  ctx.restore();
  x += 0.3;
  var loopTimer = setTimeout('draw('+x+', '+y+')', 0.1);
}

draw(0,0);

canvas {
  margin-left: 200px;
  width: 550px;
  height: 400px;
  border: 1px solid #111111;
}
<canvas id="canvas"></canvas>

Answer №1

If you're looking to effortlessly create multiple square objects, consider designing a Square Class for easy instantiation.

function squareClass () {

  //Coordinates
  this.X = 0;
  this.Y = 0;

  //Dimensions
  this.width = 5;
  this.height = 4;

  //Color for rendering
  this.color = "rgb(0, 200, 0)";

  //Square movement
  this.move = function() { this.X += 0.3; }

  //Render the square
  this.draw = function() {

    ctx.fillStyle = this.color;
    ctx.fillRect(this.X, this.Y, this.width, this.height);
  }
}

Utilize the square class whenever you need to generate new squares quickly and easily.

var squareList = [];

function createASqaure() {

  squareList.push(new squareClass());
}

By calling the createASquare function, you can introduce fresh squares into your project.

To access and utilize the methods within each square object, simply iterate through the squareList array and invoke the desired functions as shown below:

function moveAndDraw() {

  for (var i = 0; i < squareList.length; i++) {

    squareList[i].move();
    squareList[i].draw();
  }
}

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

When trying to upload a file with ng-upload in Angular, the error 'TypeError: Cannot read properties of undefined (reading 'memes')' is encountered

Struggling with an issue for quite some time now. Attempting to upload an image using ng-upload in angular, successfully saving the file in the database, but encountering a 'Cannot read properties of undefined' error once the upload queue is comp ...

Closing the Angularstrap dropdown when clicking elsewhere

Is there a method to close an angularstrap dropdown only when clicking outside of it? The current behavior is that it closes when you click inside the dropdown. Thank you ...

IE11 displaying empty placeholders instead of PrimeNG icons after deployment on server

Currently, I am in the midst of an Angular project that heavily relies on PrimeNg for various components. While everything runs smoothly when testing the project locally across all browsers (including IE11 and Chrome), a hiccup arises once the project is ...

Ensure your Vue components have type-checked props at compile time when using TypeScript

I have encountered an issue while using Vue.js with Typescript. The code I am working with is pretty straightforward, utilizing vue-class-component and vue-property-decorator. <script lang="ts"> import { Component, Prop, Vue } from 'vue-pro ...

Guide to generating a new element and displaying updated data whenever it is retrieved in a React application

I'm completely new to React and I'm struggling with rendering and listing data fetched from Firebase on my HTML page. I attempted the following approach: const Music = ({ match }) => { const [titles, setTitles] = useState([]); // Change ...

Testing React components with Jest by mocking unnecessary components

Consider a scenario where we have the Page component defined as: const Page = () => <> <Topbar /> <Drawer /> <Content /> </> When writing an integration test to check interactions within the Drawer and Con ...

What is the best way to utilize JavaScript in order to eliminate a tag when an option is chosen within an HTML form?

I'm in the process of designing a website for an artist. The website includes a contact form, and I'm currently working on a JavaScript script to remove the hidden class that I applied to the commission rules section. The goal is to make this sec ...

Issue with passing JSON data to a PHP file using CURL

I am currently working on a project that involves sending exam data with the exam-name and the selected number of questions from a list. Here is the project architecture I am following: To send JSON via AJAX to my make_exam.php file The questions.php fil ...

Creating and fetching CSV files using PHP and AJAX

I have successfully created a PHP script that generates a CSV file for automatic download by the browser. The code below shows a working version with sample data for different car models. <?php $cars = array( array("Volvo",22,18), array("BMW",15,1 ...

Repositioning the final row to the bottom of the container in Bootstrap 4

I am working on a simple footer design that includes contact information in three rows. The first two rows should appear at the top, while the last row needs to be positioned at the very bottom of the container. To achieve this layout, I decided to use abs ...

$http promise chain executing in an incorrect sequence

As a beginner in angularjs, my objective is straightforward. I aim to execute an ajax request to fetch data and, upon completion, I want to initiate a second call to retrieve another set of data based on the information from the initial set. To achieve th ...

Any suggestions on how I can make my modal stand out more?

I'm having trouble getting the modal to show up in this HTML file. Do I need to add something here or somewhere else? Do I also need to write a button onclick function? The modal should display when the "delete" button is clicked. <div class=" ...

Strategies for managing the result of findElements?

Snippet A resultsBoard.findElements(By.css(mySelector)).then(function(elements) { elements.forEach(function(val, idx) { elements[idx].getText().then(function(text) { console.log(text); }); }); }); Snippet B resultsBoard.findElements( ...

Customize the appearance of the "Collapse" component in the antd react library by overriding the default styles

Incorporating JSX syntax with *.css for my react component. Displayed below is the jsx code for the antd collapse section. <Collapse defaultActiveKey={["1"]} expandIconPosition="right" > <Panel header="This is p ...

Creating a seamless integration between a multi-step form in React and React Router

I've been learning how to use React + ReactRouter in order to create a multi-step form. After getting the example working from this link: , I encountered an issue. The problem with the example is that it doesn't utilize ReactRouter, causing the ...

Placing an order and obtaining the associated reservation_id through the use of SQL, PHP, and an html5 form

I have multiple forms with distinct purposes: The first form collects information such as the reservation date, customer details, and the table assigned for that specific date. In the second form, I capture data to place an order. This includes entering ...

Creating an inverted curve or border-radius for a div element is a design technique that can add

I've been tackling a project that requires me to style the border of a div in an inverted manner. To achieve this, I'm limited to using only CSS and JS without any plugins. I've searched through various online resources and similar questions ...

When I resize the screen size, my multiple item carousel in Bootstrap is failing to adjust and collapses

Whenever I try to resize the output screen, the carousel collapses and the last few items disappear. I really need the carousel to stay intact even when resizing. Can someone please assist me with this issue? Link to my CodePen ResCarouselSize(); $(w ...

Utilize AngularJS's OrderBy feature to iterate through the list for navigation in ascending order by Index

I am looking to customize the order of an Object-array using ng-repeat based on their index keys in ascending order. $scope.paneContainer = {books:[{}] } ; $scope.paneContainer.books[0].science = { title:"science", content:"web/app/views/partials/scienc ...

Issues with hydrating React local storage hook in custom implementation within NextJS

Currently facing an issue while implementing the localstorage hook in NextJS. The error message I am encountering is: Error: Hydration failed because the initial UI does not match what was rendered on the server.. Any suggestions on what might be causing ...