Assistance Needed: Troubleshooting Errors in Javascript Canvas Grid Output

Hey there, I'm trying to create a JavaScript/canvas grid but running into some issues. Here's what I have so far in my code: var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d");

            var width = 600;
            var height = 700;

            canvas.width=width;
            canvas.height=height;

            function Cell(x,y,width,height){
                this.x=x;
                this.y=y;
                this.width=width;
                this.height=height;
                this.draw=function(){
                    ctx.rect(this.x,this.y,this.width,this.height);
                    ctx.stroke();
                }
            }

            var x = 0;
            var y = 0;
            var width = 20;
            var height = 20;

            var cell = new Cell(x,y,width,height);

            var rows = 35;
            var cols = 30;

            function drawGrid(){
                for(var i=0; i<rows; i++){
                    for(var j=0; j<cols; j++){
                        cell.y+=cell.height;
                        cell.x+=cell.width;
                        cell.draw();
                    }
                }


            }

            setInterval(drawGrid,1);

I've managed to get it working somewhat as seen here: The current grid progress I'm hoping to expand this and fill the screen with rectangles. Any assistance would be greatly appreciated! :)

Answer №1

If you're looking to create a grid of boxes, here's a simple solution:

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

// Adjust these values if you want a different grid size
const gridHeight = canvas.height;
const gridWidth = canvas.width;

const boxSize = 20; // Size of each box

for(let i = 0; i < gridHeight / boxSize + 1; i++){
  // Draw Horizontal Lines
  ctx.moveTo(0, i * boxSize);
  ctx.lineTo(gridHeight, i * boxSize); 
  // Draw Vertical Lines
  ctx.moveTo(i * boxSize, 0);
  ctx.lineTo(i * boxSize, gridWidth);
}

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

Show a visual content in Grails Server Pages created through a specific class

In my class file, I have the image path displayed as shown below: String val; val+= "<img src=/"PATH_TO_FILE/" alt=/"sometext/">" Now, I am attempting to load the image in a gsp view within a div using jQuery from the val variable. The image is be ...

Can the functionality of ngIf and async pipe be replicated within the component's code?

With a form component and a thank you page, I am faced with the challenge of sharing data between these two components using rxjs ReplaySubject. The full code listings can be found here. In my implementation, I am utilizing ngIf and the async pipe to hand ...

"Encountering a Type Error while implementing AutoComplete ajax in a Spring MVC

I'm encountering an error in the jquery.autocomplete.min.js script: TypeError: d is undefined This issue is happening within my home.jsp file: <head> <script src="<c:url value="/resources/core/jquery.1.10.2.min.js" />"></s ...

Is it possible to conceal the text specifically inside a textarea, rather than just hiding the entire textarea itself?

Is it possible to have a button next to the textarea that allows you to hide and unhide the text inside the textarea by clicking on it? ...

A guide on updating div IDs using jQuery sortable when an element is moved by the user

My goal is to use jQuery sortable to allow users to rearrange elements on a page by dragging and dropping them. Each div element has a unique ID, and when the user swaps elements, I want to update the IDs accordingly and alert the new order so it can be sa ...

I am having trouble with my React tutorial for tic tac toe as the handleClick function is not receiving the

Currently, I am working my way through the React tutorial available at: https://react.dev/learn/tutorial-tic-tac-toe My current challenge lies in passing a value to the handleClick function to determine which square should be set to 'X'. Despi ...

Troubleshooting issue for Symfony4: Bootstrap 4 JavaScript functionality not functioning

Having some trouble implementing Bootstrap 4 with Symfony 4 using yarn package manager. The JavaScript isn't functioning properly - no errors in the console, but when trying to open the navbar by clicking the collapsed button, nothing happens. Here i ...

Insert the text into a table data cell once the drop-down selection has been changed

I am attempting to display my ajax results in the td element next to my dropdown menu that triggers the ajax call when changed. Each row contains a similar id where I intend for the text to be shown (I'm sure there is a simpler solution). Below is my ...

Top tips for sending parameters from JavaScript (using jQuery) to a Java-powered REST API?

I have developed a customized jQuery widget with the following configuration: jQuery("#foo").widget("service", { output : "test_output_field", parameters : {'format' : 'json', 'limit' : 20, ...

Create a user-friendly responsive tooltip in Javascript/jQuery with a convenient close

Looking to implement a tooltip feature that appears when a text box is focused on my responsive website, and disappears when it loses focus. Can anyone recommend the best JavaScript/jQuery library for this specific purpose? Here are my requirements: T ...

Firefox: repeated occurrences of style sheet in developer tools

I am currently managing a sample website with multiple linked style sheets at . One of these style sheet links needs to be toggled on and off, hence it includes a unique id: <link id="sketch" rel="stylesheet" type="text/css" ...

Hiding and showing div elements using CSS, JavaScript, and PHP

Here is the current code snippet: <? while ($row1 = mysql_fetch_object($result1)) { echo '<a href="#" onclick="showhide("'.$row1->id.'");">Name</a>'; while ($row2 = mysql_fetch_object($result2)) { ...

The program continues running even after the asynchronous function is executed

I am new to using postgresql. After successfully connecting to a cloud database and retrieving data using the 'postgres' package in nodejs, I noticed that the program doesn't terminate even after logging all the retrieved data on the consol ...

Issues with AngularJS UI Router functionality are being experienced specifically on localhost

What is causing the discrepancy in UI-Router functionality between JSFiddle and localhost? The localhost link is http://127.0.0.1:54046/preview/app/index.html. Have I overlooked something crucial here? There are no visible JS errors present in the console. ...

What is the method for storing a SQLite index in a variable using Nodejs?

In order to complete a homework assignment, I am using express and Node.js to create a chatroom. The messages are being stored in a SQL .db file with an integer primary key that auto-increments. There are three additional columns for text information: room ...

Images on web pages are automatically resized to fit into a smaller preview window

Currently, I am facing an issue with the display of images in my grid windows on my website . The images are appearing as partial representations instead of rescaled versions where the whole picture is resized to fit the grid window. I have attempted mod ...

Error occurred in next.js environment file when referencing process.env keys as strings in .env.local file

I have a .env.local file with various values stored in it. NEXT_PUBLIC_GA_ID = myvariablevalue I created a function to validate the presence of these values: export const getEnvValue = (name: string, required = true) => { const value = process.env[na ...

Designing a unique shape geometry using THREE JS

I've been struggling to replicate an existing city in a 3D environment using THREE.js. I have coordinates for approximately 1000 buildings, each with a varying number of corners making it impossible to use standard cubeGeometry. I attempted to create ...

Attempting to use the getCurrentUrl() function to retrieve the current URL and subsequently opening it in a new tab

I am attempting to retrieve a URL and open it in 3 new tabs, but encountering errors in the process: browser.getCurrentUrl().then(url => { browser.actions().keyDown(protractor.Key.CONTROL).sendKeys('t').perform(); browser.sleep ...

Revert the Vue State When Navigating Back in the Browser

Background In our checkout process, we redirect to Stripe after creating an order object through an API request. To prevent users from clicking the "checkout" button multiple times during this process, we toggle a variable value to show a loading icon whe ...