Preventing Canvas Image Disappearance with JavaScript's onload Event

My current issue involves adding an Image to my webpage. However, every time I hit the refresh button, the image disappears. After researching on Stack Overflow, it was suggested to include window.onload=yourDrawFunction() in the code. Despite following this advice and naming my function 'draw', the problem persists. Below is the code snippet:

<!DOCTYPE html>
<html>
    <head>
        <title>Transformation Demo</title>
        <style type="text/css">
            .hidden{
                display: none;
            }
        </style>
    </head>
    <body>
        <h1>Tranformation Demo</h1>
        <img class = "hidden" id="goku" width="220" height="277" src="goku.jpg" alt="Goku Pic">
        <canvas id="surface" width=400 height=400>
            Your browser doesn't support canvas tag.
        </canvas>
        <script>
            function draw(){
                var drawing=document.getElementById("surface");
                var con=drawing.getContext("2d");
                var gokupic=document.getElementById("goku");

                con.save();
                con.translate(100,100);
                con.rotate(Math.PI / 4);
                con.scale(3.0,1.5);
                con.drawImage(gokupic, -25,-25,50,50);
                con.restore();

                con.strokeStyle="red";
                con.lineWidth=5;
                con.strokeRect(0,0,200,200);
            }
            window.onload=draw();
        </script>

    </body>

</html>

Thank you for any help provided.

After experimenting, I found that simply using the window.onload function without naming a separate draw function works perfectly fine. This leads me to wonder why this method functions while utilizing the draw() function does not produce the desired result?

Answer №1

Explanation for why the code window.onload = someFunction() does not work while window.onload = someFunction does work.

When using window.onload = someFunction(), it sets the "onload" variable to the result of calling someFunction. Unless someFunction itself returns a function, this may not achieve the desired outcome.

The default behavior is for the onload function to be called with a single "event" argument. If you need to pass arguments, consider implementing it like this:

window.onload = function (event) {
  someFunction(argument1, argument2)
}

For more detailed information, check out this link.

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

When invoking a Javascript function within an onclick event, make sure to avoid creating a new

There's a function named save in my code that is responsible for saving data from a timer. The Model class looks like this: var Schema = mongoose.Schema; var Timer = new Schema({ Time: {type: Number}, Desc: {type: String}, Doc: {type: S ...

Selenium WebDriver is struggling to locate an element using link text

I'm currently facing a challenge in selecting an element that contains an anchor within a paragraph inside a div. The HTML structure I am working with is as follows: <a class="item" ng-href="#/catalog/90d9650a36988e5d0136988f03ab000f/category/DATA ...

What is the Proper Way to Add Inline Comments in JSX Code?

Currently, I am in the process of learning React and I have been experimenting with adding inline comments within JSX. However, when I try to use the regular JavaScript // comments, it leads to a syntax error. Let me share a snippet of my code below: const ...

Generating div elements dynamically and applying styles

Generating a div dynamically and adding style to it var newDiv = document.createElement('div'); newDiv.setAttribute("id","dynamic-div"); document.body.appendChild(newDiv); // Simulating dynamic ajax content loading $(document).ready(function () ...

Applying Bootstrap Style to an Inline Select Element: A Step-by-Step Guide

Currently working on a page layout using Thymeleaf and Bootstrap 5. I have divided the page into two parts, with this section behaving as desired: <main role="main" class="pb-3"> <br> <p>Post office ex ...

Redefining the onClick function in the Redux 'presentation' component to include parameters

How can I pass an object as an argument to a function in a redux "presentation component" efficiently? In my <BookList /> container component, I display a <BookListRow/> presentation component for each book. I want to add a button in each Boo ...

Toggle between the Angular test/development module and the production module

Currently, I am working on implementing an Angular app. During my e2e tests, I encountered a need to mock some server requests while allowing others to pass through using e2e httpBackend. Vijitta has provided an example of how to utilize the HttpBackend: ...

Experiencing a TypeError message while attempting to send header data with the nodejs request module

function loginUser(req, res) { console.log(req.body.loginemail); console.log(req.body.loginpassword); var options = { uri: webServiceURL.login,   method: "POST", body: { "login": req.body.loginemail, ...

Add a color gradient to text as it animates without displaying any code tags (HTML, CSS, JS)

I have a unique text animation that loads when the page loads. The characters will be gradually written to the screen with some words having a gradient effect. While I've managed to successfully apply the gradient, there seems to be a pause when it re ...

Modifying the Background Color of a Header in React Native

As a newcomer to React Native, I am attempting to change the background color of the header bar (Navigation Bar). Here are some approaches that I have tried: return ( <View style={styles.container}> <NavigationBar titl ...

Leveraging Angular Dragula without the need for RequireJS

I'm eager to incorporate Drag and Drop functionality into my Angular project with the help of the angular-dragula module (https://github.com/bevacqua/angular-dragula). However, it appears that this module heavily relies on RequireJS. My experience wit ...

Customizing the Switch component individually for each item fetched from an API in React Native

I'm struggling with setting the switch button individually for each item in my API. Despite trying multiple solutions, none of them seem to work for me. const results = [ { Id: "IySO9wUrt8", Name: & ...

Block Button styles not displaying in IE when set to Full Width

I can't figure out why, but it seems to be functioning properly on every other internet platform except this one. The first picture shows the button in IE, the second contains the code, and the third displays the button in Chrome. Visit webpage ...

Utilize Google Chrome Developer Tools to interact with the "Follow" buttons on the webpage by clicking on them

https://i.stack.imgur.com/W32te.png Here is the script I am currently using: document.querySelectorAll('.components-button components-button-size-mini components-button-type-orange desktop components-button-inline').forEach(btn => btn.click() ...

Encountering the issue of receiving an undefined value for a variable despite having previously defined it within

I’ve been working on implementing the Google Maps distance matrix API with the google-distance-matrix library. Here’s the code snippet I’m using: app.get("/users", (req, res) => { // console.log(req.query); // res.send(req.query); ...

What is a way to retain the value of a variable after a request, while starting off with a different value on the initial load?

In my Flask application, users have the option to choose a specific time period with a start date and an end date. When the page initially loads, I want the start date to default to the first day of the current month and the end date to be the current day. ...

Issue with receiving output from tessearct.js in PDF format

I am currently working on a basic javaScript OCR (Optical Character Recognition) application using tesseract.js. I have included {tess_create_pdf: "1"} in the .recognize() method to receive the result in PDF format, but it seems to be malfunctioning. Can ...

splitting lengthy words into several lines

Does anyone know how to break words like the examples below using CSS or jQuery? SAMPLE 1 ConfigTechnologyHormonyAppComponentBackOfficeLaunch It needs to be broken into ConfigTechnologyHo rmonyAppComponentB ackOfficeLaunch SAMPLE 2 WorkAppComponentBa ...

The power of relative URLs in AJAX calls

Why does Javascript handle relative URLs differently than standard HTML? Consider the URL provided: http://en.wikipedia.org/wiki/Rome. Launch a Firebug console (or any other Javascript console) and type in the following: var x = new XMLHttpRequest(); x.op ...

Ensuring Consistent Headings While Scrolling

Imagine having headings structured like this: <h1 class="fixontop">heading 1</h1> content goes here. . . . long paragraph. <h1 class="fixontop">heading 2</h1> 2nd content goes here. . . . long paragraph. <h1 class="fixontop"> ...