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

Troubleshooting: Unable to preview Facebook Page plugin

When I visit the Facebook developer site to get the code for a Facebook page plugin, I use this link. The preview feature works perfectly with pages like "facebook.com/Nike", but when I try it with my own page, "facebook.com/BargainHideout", it doesn&apos ...

JavaScript client side event that references the sender object ID in an aspx file

Can someone provide assistance with an issue in the code block below? function(s, e) { form1.hfRaiseEvent.value = s.ID; } This particular function is triggered when the Client Side Click Event occurs. From my understanding, s refers to the Sender Obj ...

Tips for managing Material-ui's <Autocomplete/> component based on the option's id

When dealing with HTML select in React, it's common to use an id or key to keep track of the selected value: <select value={value} onChange={(event) => setValue(event.target.value)}> {options.map((option) => ( <option value={optio ...

Manipulate component properties using CSS hover in React with Material-UI

I am attempting to modify the noWrap property of a Typography element when hovering over it. I have defined a custom CSS class for the parent element and the hover functionality is working correctly. However, I am unsure how to adjust the noWrap property u ...

Adjust the vertical size of the slider in Jssor

Hi there! I'm currently working on a slider that I want to have a dynamic width (100% of the container) and a static height of 550px on PCs, while being responsive on mobile devices. Below is my code snippet: <div class="col-md-6 right-col" id="sl ...

Tips for ensuring elements within a modal receive immediate focus when opened in Angular 2

I am relatively new to Angular JS and I am encountering some challenges with implementing a directive in Angular 2 that can manage focusing on the modal when it is opened by clicking a button. There have been similar queries in the past, with solutions pr ...

Angular 5 with Typescript encountered a failure in webpack due to the absence of the property "data" on the Response

I am encountering an issue during webpack compilation. It compiles successfully if I remove .data, but then the page crashes with calls from template->component (which in turn calls a service). Here is the error I am facing: ERROR in src/app/components ...

Achieve text length that does not exceed the specified limit dynamically

Is it possible to determine the length of the visible portion of text that overflows (or calculate the size of the overflow for further processing) using CSS or JavaScript? If so, can this calculation be done dynamically (such as on window resize)? The g ...

I desire to activate the textbox only when the radiobtnlist value equals 1

I am trying to disable a textbox based on the selected value of a RadioButtonList in my code. However, the functionality is not working as expected and I am unsure why. <script type="text/javascript"> $(function () { $("#RadioButton ...

I am looking to change the state of only the element that is being moused over in a React Hooks useState function, rather than changing the

Currently, I have a component from line 61-67 that controls the state of an editIcon. The issue is that it changes the state values for all items in the column, rather than just the specific item or row it should apply to. When hovering over a span element ...

Creating a PHP script that retrieves data from JavaScript and stores it in MySQL can be accomplished by using AJAX to send the

Hello, I am attempting to create a PHP script that can extract coordinates from this JavaScript code (or from this link ) and store them in a MySQL database. Can someone please provide me with a tutorial on how to accomplish this? <script> var ...

Utilize Vuex mutators within route navigation guards

Hey there, I'm currently working on an app using Laravel and VueJS. To restrict certain routes, I've implemented navigation guards. However, I'm facing an issue where I need to access Vuex mutators to determine if the current user is logged ...

Error: The middleware function is not recognized | Guide to Transitioning to React Redux Firebase v3

After utilizing these packages for my project, I encountered an error in middleware composition while creating a new react app with create-react-app. Below are the packages I have included. Can someone please help me identify what is missing here? HELP I ...

Create seamless communication between Angular application and React build

I am currently engaged in a project that involves integrating a React widget into an Angular application. The component I'm working on functions as a chatbot. Here is the App.tsx file (written in TypeScript) which serves as the entry point for the Rea ...

"I am trying to figure out how to set a link to an image using JavaScript. Can someone help me

I need help figuring out how to insert an image or gif file within two inverted commas '' in this line of code: _("status").innerHTML = ''; (line number 13 in the actual code) Your assistance with this question would be greatly appreci ...

React Select streamlines dropdown options for multi-selection by abbreviating names

Is there a way to shorten dropdown names when selected similar to the example shown in the image below This is the snippet of my code : multiValue: [ { value: "BUF", label: "BUF" }, { value: "CCT& ...

Establishing a primary data format for a backbone collection

Is there a way to configure a Backbone collection to always include a content type of "application/json" in every request it makes? I have tried the following code snippets: myCollection = Backbone.Collection.extend({ headers: {"Content-Type": 'ap ...

Express POST request body is required

I am starting to learn nodejs and express, and while reviewing some code I found this interesting snippet. Can someone please explain what it means and how I can send a POST request to it using cURL? There are no specified data fields. app.post('/&apo ...

Is it possible to use require() to read a .json file from a dependent library?

Is it possible to access a .json file within one of my dependent libraries? I'm hesitant to use fs to read ./node_modules/somelib/properties.json because the library could have been installed globally. Is there a way to achieve this using require in ...

Deleting items from an array in ReactJS

When retrieving a list of users from AWS Cognito, everything works flawlessly. However, the task of iterating over this array and removing users that do not match a specific Client ID is where I'm facing difficulties. What am I doing wrong in this sc ...