The difference between calling a function in the window.onload and in the body of a

In this HTML code snippet, I am trying to display the Colorado state flag using a canvas. However, I noticed that in order for the flag to be drawn correctly, I had to move certain lines of code from the window.onload() function to the drawLogo() function. This led me to believe that there might be an issue with the global variables canvas, ctx, x,, and y. I need these variables to be truly global because I plan to utilize them in other functions that will interact with the same canvas.

I confirmed that window.onload() is functioning properly as I can draw the flag by calling drawLogo() within it.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Logo</title>
<script type="text/javascript">

var canvas;
var ctx;
var x;
var y;

window.onload = function () {
    canvas = document.getElementById('logo');
    ctx = canvas.getContext('2d');
    x = canvas.width;
    y = canvas.height; 
};

var drawLogo = function() {   
    var radius = 23;
    var counterClockwise = false;

    ctx.beginPath();
    ctx.rect(3, 20, 75, 30);
    ctx.fillStyle = 'rgba(0,0,255,0.8)';
    ctx.fill();

    ...

};

</script>

</head>
<body>
     <div>
       <canvas id="logo" width="600" height="150"></canvas>
       <script type="text/javascript">
         drawLogo();
        </script>
     </div>
</body>
</html>

Answer №1

When the entire page has finished loading, <code>window.onload
is triggered. This means all CSS, JS files, fonts, images, and other resources have been downloaded.

On the other hand, your drawLogo function is called as soon as the script tag is evaluated during the page load process.

The issue here is that the drawLogo function is being executed before the global variables are populated.

An easy fix would be to place the drawLogo function inside the window.onload function. Additionally, consider replacing the onload event with a faster onready event for better performance.

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

Install the canvas package on MacOS M2 using npm

Encountering an error while attempting to install canvas on my nextJS 13 project. Here is the error message: npm ERR! code 1 npm ERR! path /Users/user1/Projects/Raccord/webapp/node_modules/canvas npm ERR! command failed npm ERR! command sh -c node-pre-gyp ...

Exploring Nextjs with server-side rendering and fetching data from

When utilizing the getServerSideProps function in Next.js to make a fetch request to my API, I encountered an issue where the origin header was coming back as undefined. This seems to be specific to requests made from the server in Next.js, as I am able ...

What is the best way to merge two approaches for tallying items within each category?

I have an Angular 8 application that includes two methods for displaying the number of items in each category. These items are retrieved from the back-end and are categorized as follows: <mat-tab> <ng-template mat-tab-label> ...

Nested tables in Datatables retrieving child table rows based on parent table

I have been struggling for the past three days to get my nested Datatables working properly. I have a parent table called MAINtable and a child table called adjlinesTable. The issue I am facing is that all lines from the adjlinesTable are being drawn to ...

What is the best way to ensure a function waits for a stable database connection before proceeding?

Perhaps not phrased well, but I grasp the concepts of async/promises/callbacks. My aim is to develop a module that can be imported (database.js), where I can then execute methods like database.insert() and database.read(). This is the code I have so far: ...

Upon upgrading to webpack 5.x, I encountered the error message `Error: getaddrinfo ENOTFOUND localhost:8081` when trying to run `npm run serve`. What could be causing

Recently, I was tasked with upgrading a Vue project from webpack 4.x to webpack 5.x. Prior to the upgrade, my vue.config.js file looked like this: devServer: { port: 8081, public: process.env.PUBLIC_ADDRESS, }, The variable PUBLIC_ADDRESS was defined ...

Can the autoscroll offset be adjusted while dragging?

I am developing a single-page application using Vue.js. The user interface consists of three main components: A fixed navbar at the top with a z-index of 2 A fixed sidebar on the left with a z-index of 1, and padding to accommodate the navbar A central ar ...

AngularJS: Issue with inputMask functionality within an angularJS table

Within my ng-repeat table, I have two date fields. Here is the code snippet: <tr ng-repeat="ol in orderLines"> <td> <input class="audioStartTime" type="text" ng-model="ol.AudioStartTime"/> </td> <td> ...

Animating with React JS using JSON data sources

Currently, my project involves using React/Redux to store animation data in JSON and display it on a React page. The challenge lies in implementing the animations correctly while utilizing setTimeout for pauses and setInterval for movement. The Animation ...

Converting a nested JavaScript array into a PHP array

Having a javascript array is how my dilemma starts: foodList = ([apple,10,],[banana,20]) To convert this to a json object and send it to php, I perform the following action: var jsonData = JSON.stringify(foodList); The challenge now is extracting values ...

Tips for aligning pagination in the MUI v5 table component and creating a fixed column

I am currently experimenting with MUI table components and have created an example below with pagination. const MuiTable = () => { const [page, setPage] = useState(0); const [rowsPerPage, setRowsPerPage] = useState(5); const [data, setData] ...

"Scotchy McScotchface's to-do list application powered

How is the index.html (frontend Angular) being triggered? The tutorial mentioned that by including one of the following routes in route.js, the frontend gets called app.get('*', function(req, res) { res.sendfile('./public/index.html&ap ...

Can you provide guidance on implementing StyledComponents within the app folder of Next.js version 13?

Quoting information from the Next.js documentation: Attention: CSS-in-JS libraries that rely on runtime JavaScript are currently not compatible with Server Components. The following libraries are supported in Client Components within the app directory: s ...

Determining If a setInterval Function is the Sole Factor Preventing an App from Exiting

Is there a method to determine the number of tasks remaining for Node before it automatically exits because all tasks are completed? I am interested in utilizing setInterval but only while the application is still running other processes. I do not want t ...

The .env file is functioning properly for the current keys, but any new ones I include remain undefined

Recently, I took over a Vue application that utilizes axios. Within the dataService.js file, it retrieves URLs from a project's .env file using process.env.FOO_BAR for GET requests. The pre-existing key-value pairs such as VUE_APP_DATA_URL function p ...

What is the method for obtaining the selected option value while hovering over a dropdown list option?

Hello, I am using the Chosen jQuery plugin to select image options. When I change the trigger, I can easily get a value. Now, I want to be able to get the value when I hover over an option in the select dropdown menu, like shown in the image below, and dis ...

Modify the website address and show the dynamic content using AJAX

$(function(){ $("a[rel='tab']").click(function(e){ //capture the URL of the link clicked pageurl = $(this).attr('href'); $("#Content").fadeOut(800); setTimeout(function(){ $.ajax({url:pageurl+'?rel=tab&apo ...

Verifying the username's availability through AJAX requests

My registration form utilizing AJAX isn't connecting to the database. It seems like I'm missing something important. Let's focus on validating this particular field: Username:<input type="text" name="user" id="user" maxlength="30"> & ...

retrieve information in json format from a specified web address

I need to figure out why the data from a specific URL is not being displayed properly on my node application. It seems like there might be an error in my code. const extractRefDefaultSchema = async (data) => { const url = "https://mos.esante.gouv.f ...

What is the best way to extract valid objects from a string in JavaScript?

Currently, my data is being received through a TCP connection. To determine if a string is a valid JSON object, we use the following method: let body = ''; client.on('data', (chunk) => { body += chunk.toString(); try { ...