Typescript: Why Lines Are Not Rendering on Canvas When Using a For-Loop

What started out as a fun project to create a graphing utility quickly turned into a serious endeavor...

My goal was simple - to create a line graph.

Despite my efforts, attempting to use a for-loop in my TypeScript project resulted in no output.

In the source code below, you'll notice console logs placed strategically to verify certain actions. In my TypeScript project, they all execute perfectly and in the intended sequence.

Since Stack Overflow doesn't provide support for TypeScript, here is a link to a CodePen containing the complete source code along with the TypeScript compiler: https://codepen.io/SkylerSpark/pen/zYvpWNZ

The section causing me trouble is as follows:

g.px & g.py represent my coordinates, extracted from this sample array (depicting pizza sales data):

const pizzas = {
    x: [0, 5, 10, 15, 20, 25, 30, 35, 40],
    y: [0, 1, 2, 3, 4],
    px: [0, 5.2, 7, 20.9, 34.3, 39.5],
    py: [0, 1.1, 1.3, 2.7, 3.5, 3.9]
};
// Drawing Numbers
if (g.px.length == g.py.length) {
    console.log("confirm");
    for (var i = 1; i < g.px.length + 1; i++) {
        if (i == 1) {
            console.log("start");
            ctx.beginPath();
            ctx.moveTo(g.px[i], g.py[i]);
        } else if (i < g.px.length) {
            console.log("continue");
            ctx.lineTo(g.px[i], g.py[i]);
        } else {
            console.log("draw");
            ctx.stroke();
        }
        console.log(i);
    }
}

Take a look at the image below illustrating that everything runs smoothly: https://i.stack.imgur.com/WkA3M.png

Answer №1

The issue lies in the fact that your y-values need to be negative. In scenarios like this, it can be beneficial to simply sketch a line first rather than immediately resorting to loops. I discovered this by integrating the code snippet below:

        ctx.beginPath();
        ctx.moveTo(-40, -40);
        ctx.lineTo(40, -40);
        ctx.lineTo(40, 40);
        ctx.lineTo(-40, 40);
        ctx.stroke();

This small adjustment just before constructing the line actually yielded some visible outcomes. By replacing g.py[i] with -g.py[i] throughout, a slight line appears at the bottom left of the graph. I hope this solution proves useful!

https://i.stack.imgur.com/LVvBc.png

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

Tips for utilizing CSS container queries in conjunction with the Material-UI framework

I'm looking to implement CSS container queries with MUI. In my code, I want to change the background color to red if the parent width is less than 300px. Check out the sandbox const StyledItem = styled("div")(({ theme }) => ({ border: ...

When utilizing forEach to loop through and interact with elements in React Testing Library, the onClick event handler is not triggered. However, employing a for loop successfully triggers the

In my React project, I've created a functional component called Shop. It accepts a callback function as a prop and displays a list of items. Each item in the list triggers the callback when clicked. function Shop(props) { const { onClickMenu } = p ...

Implementing subscriber addition on Mailchimp 3.0 using Node.js and HTTPS

Here's the content of my app.js file: const express = require("express"); const bodyParser = require("body-parser"); const request = require("request"); const https = require("https"); const app = express(); app.use(express.static("public")); app.u ...

Closing an Angular Modal Service from External Elements - Learn the Techniques

This is the official angular-modal-service Github page. If you're looking for some examples, check out the angular-modal-service examples here. For my current project, I am working on developing a "Custom Modal" without relying on Bootstrap. Here&ap ...

Leveraging the content delivery network for react-select in a react.js project

I'm having trouble using react-select with cdn. I attempted to download the cdn for react-select but keep encountering an error stating that 'select is not defined'. I also tried downloading the zip package for react-select, but I am unsure ...

Implementing a dual hover effect on a Div element

I am working with HTML code that includes an image and text <div class="subcontainer1"> <img src="a.png" alt="" class="imgcolumn"> <h3 class="header3">Hello</h3> </div> This setup places the content above the image. ...

A: TypeScript Error TS7006: Parameter implicitly has an 'any' type

TS7006: The parameter 'port' is implicitly assigned an 'any' type. constructor(port) { TS7006: The parameter 'message' is implicitly assigned an 'any' type. Emit(message) { I'm confused because all the other r ...

Finding a specific document in MongoDB using a unique slug within Next.js: A step-by-step guide

I have a collection of data in MongoDB structured like this: [ { "Post": "this is a post", "_id": ObjectId("630f3c32c1a580642a9ff4a0"), "slug": "this-is-a-title", "title" ...

Exploring the TypeScript compiler API to read and make updates to objects is an interesting

I'm delving into the world of the typescript compiler API and it seems like there's something I am overlooking. I am trying to find a way to update a specific object in a .ts file using the compiler API. Current file - some-constant.ts export co ...

Navigate to a specific moment in an HTML5 audio track by clicking on the progress bar

<html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> <script> $(document).ready(function(){ var counter = 0; ...

Verify whether a class or id is present in the HTML response obtained from an AJAX request

Is there a way to check the content of HTML returned by an AJAX call before rendering it to avoid any flickering effect? I am aware of using hasClass() to check for classes, but in this scenario, the AJAX response is returning HTML. I can append the HTML ...

For Firefox, the status code always comes back as 0 when using xmlhttprequest

When attempting to make asynchronous calls using the xmlhttprequest object, everything functions perfectly in Internet Explorer. However, Firefox seems to be encountering issues. Here is a snippet of the problematic code: if (req.readyState == 4) { i ...

Troubleshooting drag-and-drop functionality in a JavaScript HTML5 application resembling a Gmail upload interface

Here is a snapshot of my user interface: Each node in the tree structure is represented by an <li> element along with an <a> link. Furthermore, each folder serves as a dropzone for file uploads similar to the drag-and-drop feature found in Gm ...

Steps for including a font ttf file in Next.js

As a newcomer to Nextjs, I am eager to incorporate my own custom fonts into my project. However, I find myself completely bewildered on how to execute this task (my fonts can be found in the "public/fonts/" directory). The contents of my global.css file ar ...

Fullcalendar in Angular fails to update events automatically

I am exploring the integration of fullcalendar with angular. Despite adding valid events to my events field, they are not displaying in the UI. However, hardcoded events are appearing. I am relatively new to angular, so the issue may not be directly relat ...

Encountering an obscure package error while attempting to install an NPM package

After running the following command on my node application: npm install --save-dev typescript I encountered this error message: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="563a3f3426271667786e786e">[email pro ...

"Provide information, then open a new webpage by clicking on a button. Perform various actions with the form by using type

Is there a way to quickly submit form entries to my database and then automatically redirect to a new page? My current situation requires that submitted information is stored in the DB before directing users to a thank you page, all in one seamless click! ...

What is the proper way to tap into the features provided by DefinitelyTyped in typescript?

While working on my Angular2 app that deals with money amounts, I decided to use dinero.js to handle money values. However, I am encountering difficulties in accessing certain features in Typescript. Following the instructions, I installed the DefinitelyT ...

Unspecified locale with Next.js router

Despite extensive research and multiple attempts, I have not been able to find a solution to my problem. That's why I am reaching out for help again. Currently, I am working on a local project and I would like to implement Internationalized Routing f ...

Scrolling jqgrid to focus on the current day column and implementing a blinking effect on cells with stored data

I have a jqgrid with 38 columns of data, where the first 6 columns are frozen and the rest are unfrozen. Depending on the combo box selection, it shows either dates or months (see sample image here). After loading the grid, I want it to automatically scrol ...