The lineTo() function does not support passing in an array as its argument

My goal is to draw lines based on the coordinates provided in the array called points. However, I encountered an error when calling the method. Oddly enough, when I try to access a specific element using console.log(points[1][1]), it works perfectly. Can someone help point out what I might be missing here?

"Uncaught TypeError: Cannot read property '0' of undefined"

Below is the code snippet:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var points = [[50, 50], [50, 100], [25, 120],
             [100, 50], [70, 90], [100, 90], [70, 120]];

function drawPoints(array) {
    ctx.beginPath();
    ctx.moveTo(array[0][0], array[0][1]);
    for (var i = 1; i <= array.length; i++) {
        ctx.lineTo(array[i][0], array[i][1]);
    }
    ctx.stroke();
}

drawPoints(points);

Answer №1

Kindly review the following code snippet, which has been recently updated:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var points = [[50, 50], [50, 100], [25, 120],
             [100, 50], [70, 90], [100, 90], [70, 120]];

function drawPoints(array) {
    ctx.beginPath();
    ctx.moveTo(array[0][0], array[0][1]);
    for (var i = 1; i < array.length; i++) {   // The issue was identified here.
        ctx.lineTo(array[i][0], array[i][1]);
    }
    ctx.stroke();
}

drawPoints(points);

Answer №2

Check out this example:

 <canvas id="myCanvas" width="200" height="100" style="border:1px solid #ccc;"></canvas>


    <script>
        var canvas = document.getElementById("myCanvas");
        var ctx = canvas.getContext("2d");
        var points = [[50, 50], [50, 100], [25, 120],
            [100, 50], [70, 90], [100, 90], [70, 120]];

        drawPoints(points);

        function drawPoints(array) {

            ctx.beginPath();
            ctx.moveTo(array[0][0], array[0][1]);
            for (var i = 1; i < array.length; i++) {
                console.log("Point Value", array[i][0]);
                ctx.lineTo(array[i][0], array[i][1]);
            }
            ctx.stroke();
        }

    </script>

Answer №3

When working with arrays in JavaScript, it's important to remember that the indices start at zero. This means that the first element in an array has an index of 0, and the last element has an index of array.length - 1.

One common mistake is to iterate through an array using a for loop that goes up to array.length, which can cause an error on the final iteration.

A solution to this issue is to adjust your loop to start at index 1 instead:

for (var i = 1; i < array.length; i++) { /*...*/ }

Alternatively, you can take advantage of ES6 features by using something like:

for (const elem of array.slice(1)) {
    ctx.lineTo(...elem);
}

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

javascript The final position achieved through requestAnimationFrame is never precise

let pf = document.querySelectorAll('.pf'); for (let i of pf) { Object.assign(i.style, { left: '400px' }) } function shiftLetters() { let start = performance.now(); let dist = -400; let dur = 500; const logoAnimate = ( ...

Changing the context results in the entire component being re-rendered

Currently, I am encountering a challenge where I have two different components within my Layout.js component that need to "share" props with each other. To address this issue, I introduced a ContextProvider named IntegrationProvider. However, a new proble ...

How can I retrieve the identical fingerprint used by AWS from x.509 using node-forge?

Is there a way to obtain the certificate ID / fingerprint of an x.509 certificate using the node-forge library? Update I am trying to configure AWS IoT and believe that AWS uses a specific fingerprint algorithm to generate the certificate ID. This inform ...

Having several horizontal scrollbars at once on a single webpage

I stumbled upon a great example showcasing how to scroll a div on my page: Check out this Codepen - https://codepen.io/zheisey/pen/xxGbEOx Although, I am looking to extend this functionality to allow multiple divs to scroll together. Any suggestions? I ...

The way in which the DOM responds to adding or deleting elements from its structure

My typical method for displaying a popup involves adding an empty div tag and a button to the webpage: <div id="popupDiv"></div> <input type="button" id="popupButton" /> I then use jQuery to handle a button click event, make an ajax cal ...

Issue with timestamp in the Instagram API call to retrieve media using AJAX (GET /media/search)

My API call is returning a 400 bad request error message: {"meta":{"error_type":"APIInvalidParametersError","code":400,"error_message":"invalid parameters-check the max\/min-timestamps, if you supplied them"}} Even though my request appears to be co ...

Issue with Ajax not sending query string to ASP.NET controller

I am currently working with an Ajax function that serializes data sent from my view into a query string. Here is the code snippet: UpdateFIConfig: function ($appForm) { var valid = $appForm.valid(); //if not valid the validate plugin will take ca ...

Storing a collection of objects in session storage

I've been struggling to save an array containing the items in my online shopping cart. Even though both the object and the array are being filled correctly, when I check the sessionStorage, it shows an array with an empty object. I've spent a lot ...

Refresh a different Angular Controller after submitting a POST request

Just to clarify, I am looking to dynamically reload another controller with new data after a POST request without refreshing the page. Here is my code: No issues with saving data to the database. Script var app = angular.module('userBase', []) ...

Executing function with ng-click in AngularJS only on the second click of the button

Currently, I am studying AngularJS and working on an exercise that involves using the ng-click function. Strangely, I am only able to view the result after clicking upload for the second time. I am trying to display my json content but it's not workin ...

Step-by-step guide to start an AngularJs application using TypeScript

I have developed an AngularJS App using TypeScript The main app where I initialize the App: module MainApp { export class App { public static Module : ng.IModule = angular.module("mainApp", []) } } And my controller: module MainApp { exp ...

What is preventing my div from occupying the entire window space?

Currently, I am attempting to create a div that will occupy the entire height of the window, which is set to 640px, regardless of the content within the <h3> tag. However, I seem to be missing something in my code. I am using an emulator to run the ...

managing arrays in JavaScript with multiple tables

**I have successfully written code for calculating the sum of inputs in one table** $('#example122').on('input', '.calculate', function () { calculateTotal(); }); function calculateTotal() { var grandTotal = 0; $ ...

Transform a row into a clickable element

I am currently working on a social media platform where users can search for venues stored in the database. In my search.php file, I have implemented a text box that dynamically loads venue names from the database into a venuesearch div as the user types. ...

Tips for incorporating external libraries into a Grafana data source plugin

What's the best way to integrate an external library into a Grafana datasource plugin? My plugin is functioning properly, but I encounter an error when trying to use the "mqtt" library that I have installed and added to the package.json file: Plugin ...

Creating a Pre-authentication service for AWS Cognito using VueJS

Implementation of Pre-Authentication feature is needed in my VueJS application for the following tasks: Validation of ID/Refresh Token to check if it has expired. If the IdToken has expired, the ability to re-generate it using the Refresh Token or altern ...

Tips for creating a div that gracefully fades out its background image when hovered over, while keeping the internal content unaffected

I am looking to create a hover effect on a div element that has a background-color, background-image, and text. What I want is for the background-image to slowly disappear when the div is hovered over, while keeping the text and background color visible. I ...

Difficulty with slideToggle and other jQuery animations arises when selecting specific elements

When elements are selected from the page using the following code: $('.offers')[count - 1].slideToggle(500); The slideToggle function stops working, along with any other animations. However, this code snippet does work: $('.offers')[ ...

Enhance User Experience by Implementing Event Listeners for Changing Link Visibility Using mouseover and getElementsBy

I am new to JavaScript and struggling to find a solution. Despite searching online for fixes, none of the solutions I've found seem to work for me. I have spent hours troubleshooting the issue but I must be missing something crucial. Can someone plea ...

Experimenting with Jquery hyperlinks beyond the realm of Google Chrome

Is there a way to verify a jQuery link without relying on the inspect element feature in Google Chrome? I initially thought that was the issue because the links failed to load, but even after correcting it, the show function still does not perform the anim ...