Just a simple canvas animation

My canvas animation consists of two rectangles moving in different directions, but I believe it can be simplified further.

http://jsfiddle.net/tmyie/R5wx8/6/

var canvas = document.getElementById('canvas'),
    c = canvas.getContext('2d'),
    x = 10,
    y = 15,

    a = 20,
    b = 50;

function move() {
    c.clearRect(0, 0, 500, 300);

    c.fillRect(0, y, 5, 5),
    c.fillRect(b, 5, 15, 15);


    x++;
    y++;
    b++

    if (y > canvas.height || x > canvas.width) {
        y = 0;
        x = 0;
    }
}

setInterval(move, 100);

For instance, what if I want to add three more shapes? Currently, I would need to create additional variables for each coordinate:

    x++;
    y++;
    b++

Is there a way to transform each rectangle into its own object?

Answer №1

If you want to convert them into objects, here's an example:

function Box(x, y, w, h, dX, dY, color) {

    var instance = this;

    this.x = x;
    this.y = y;
    this.width = w;
    this.height = h;

    this.deltaX = dX || 0;       
    this.deltaY = dY || 0;
    this.color = color || '#000';  
    
    this.update = function(context) {
        instance.x += instance.deltaX;
        instance.y += instance.deltaY;
        
        context.fillStyle = instance.color;
        context.fillRect(instance.x, instance.y, instance.width, instance.height);
    }    
}

The dX and dY represent the amount by which the box should move with each update. By setting these values, you can control the movement of the object.

Using deltas allows for easy implementation of effects like bouncing (as demonstrated in the given link), acceleration, variable speed, directional movements using trigonometric functions, and more.

You can choose to use fixed values instead, but utilizing deltas provides long-term advantages (reference: this method was commonly used in classic games like Pong).

Check out the online demo

Once the object is defined, you can create multiple instances and store them in an array:

var boxes = [
    new Box(10, 10, 100, 100, 1, -2),
    new Box(100, 1, 50, 50, 2, 1, '#f00'),
    ...
]

Simply iterate through the array to update each object:

function animate() {
    context.clearRect(0, 0, canvasWidth, canvasHeight);

    for(var j = 0, b; b = boxes[j]; j++) {
        /// add conditions as needed
        b.update(context);
    }
    requestAnimationFrame(animate);
}

requestAnimationFrame(animate); /// start animation loop

Answer №2

Here is a more simplified approach, although I would suggest following Ken's method for long-term benefits. In this version, the rectangles are still represented as property bags without any inherent behavior.

var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d'),
    rects = [{x:0, y:15, w:5, h:5, vx:0, vy:1},
             {x:50, y:5, w:15, h:15, vx:1, vy:0}];

function moveRectangles() {
    ctx.clearRect(0, 0, 500, 300);

    for (var i=0; i < rects.length; i++) {
        var rect = rects[i];
        ctx.fillRect(rect.x, rect.y, rect.w, rect.h),
        rect.x += rect.vx;
        rect.y += rect.vy;
    }
}

setInterval(moveRectangles, 100);

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

Unable to retrieve a particular file from S3 while utilizing Strongloop

While I am able to upload, delete, and list folders from an Amazon S3 container using Strongloop, I am facing difficulties retrieving a specific file. This is my code: $scope.getS3Files = function(myfolderName){ //need to fetch all zip files in myfolderA ...

The relevance of this concept in the classroom setting and within the setTimeout function is integral to

Having recently started learning JS, I have gone through various answers on the context of "this" with classes and setTimeout(), but I am facing a specific issue. I am struggling to understand the thought process or mental model behind the following code ...

Vue 3's "<Component :is="">" feature magically transforms camelCase into lowercase

Within my application, I have implemented a feature where users can customize the appearance of social media links on their page by defining which platforms they want to include. Each social media platform is represented by its own component responsible fo ...

Are there any instances where CSS is overlooking certain HTML elements?

In the following HTML code snippet, the presence of the element with class ChildBar is optional: <div class="Parent"> <div class="ChildFoo"></div> <div class="ChildBar"></div> <!-- May ...

Monitoring the loading progress of multiple files using Three JS

Just starting out with Three JS and I'm on a mission to create a loading screen that displays the progress of assets being loaded for a scene. I have a total of 7 different types of assets, including: 4 GLB files 2 Texture files And 1 Obj file Acco ...

Node.js Friendship NetworkIncorporating Friendships in Node

Currently, I have successfully set up a real-time chat application using node.js and socket.io. My next goal is to allow users to create accounts, search for other users by username, and send friend requests to start chatting. I have tried searching onlin ...

Tips for transferring data between iframes on separate pages

I am currently working on implementing a web calendar module within an iframe on page-b. This module consists of 1 page with two sections. Upon entering zipcodes and house numbers, the inputs are hidden and the calendar is displayed. The technology used he ...

`Incompatibility with Internet Explorer causes AJAX loader GIF to fail when using asynchronous POST requests`

Is there a way to display an AJAX loader gif during an asynchronous POST request on Internet Explorer? It seems that the request process stalls and the updated content is not visible when using Internet Explorer. However, everything works fine on browser ...

What is the best way to retrieve the name of an element or component using JavaScript

I'm currently working on a webpage that includes ASP.NET panels and JavaScript which retrieves all components present on the page: var items = Sys.Application.getComponents(); My goal is to obtain the name/ID of each element stored in the 'item ...

Iframe not displaying Base64 encoded PDF in Chrome App

Currently, I am in the process of developing a Chrome App that essentially acts as a wrapper for the main app within a webview. The webview sends a Base64 encoded PDF as a message to the app, which then creates a hidden iframe and loads the PDF into the fr ...

Reposition the checked box to the top of the list

My goal is to click on each item, and the selected item should move to the top of the list and be rendered at the top. However, I encountered an issue where when clicking on an item, it moves to the top but the item that replaces it also gets checked. Bel ...

Utilizing Javascript to Open a New Tab from Drupal

I'm attempting to trigger the opening of a new tab when a specific menu link is clicked within a Drupal website. My initial approach was to incorporate JavaScript directly into the content of the page, but unfortunately this method has not been succes ...

Error in React+Redux: Trying to access the "address" property of a null value is not permitted

I am new to using react and encountering an issue with my ecommerce app. The app runs smoothly until I log out and then log back in at the shipping address page, which triggers the following error: TypeError: Cannot read property 'address' of nu ...

The Recharts Line chart fails to display newly added data points when data is updated

My app features a straightforward tool that enables users to monitor their weight changes over time. Despite successfully receiving new data in the props, the chart does not update and display the new point. Recharts Component: import React from 'rea ...

Display the current count of selected radio buttons in real-time

I am working with radio buttons that are generated dynamically using a 2D array within a while loop. I want to display the number of radio buttons checked when one is clicked. Here are my radio buttons: $n=0; while($row=mysqli_fetch_row($rs)){?> <f ...

Hide HTML div on click

Why does the button disappear when I click on it, but the status refreshes? Javascript $( ".refreshstatus" ).click(function(){ $( ".navplayers" ).load('stats.php'); }); CSS .refreshstatus{ font-family:'Noto Sans'; font-w ...

Validating Password Consistency using Javascript

I'm having trouble with validating the password fields and ensuring they match, even when both input boxes contain the same password. JavaScript var validator = $("#signupform").validate({ rules: { password: { required: true, minle ...

If there are multiple Monaco diff editors present on a single page, only the first instance will display the diff

I'm currently working with a Vue component that renders a diff editor using Monaco. However, when I have more than one instance of this component on the same page, only the first one displays the diff highlights. Here is the template: <template> ...

``I am experiencing difficulties with utilizing a personalized color scheme in React JS with Material

I'm currently working on customizing the color palette for my project, but I am only able to modify the main attribute and not others. My development environment is JavaScript with MUI, not Typescript. import './App.css'; import {BrowserRout ...

There is no need for updates as git is already current for some mysterious reason

As a newcomer to git, I've been trying to wrap my head around it but still struggling. Can someone help clarify this for me? My question pertains to the 'master' branch in git which contains the following code: const list = [ 'h&ap ...