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

Having difficulty locating the identification number of an item within the HTML coding

I'm currently trying to locate the ID of the "proceed to checkout" button for a bot that I am developing for my mother on the Best Buy website. However, it seems like the button's ID is hidden and I'm unable to determine how to uncover it. A ...

Enhancing code branch coverage using Istanbul

The code snippet provided has a branch coverage of only 50% (refer to the coverage report below). I am unsure how to enhance this as there are no if statements present. I suspect that Istanbul must utilize some form of measurement that I have yet to grasp ...

Cross-Origin Resource Sharing problem: "Preflight request response does not meet access control criteria"

I'm currently tackling a Vue.js/Nuxt.js project that involves sending API requests to 'https://app.arianlist.com'. However, I've encountered some CORS challenges and came across this error message: "Access to XMLHttpRequest at &ap ...

Need to specify a parameter type for the input tag in HTML

Currently, I am developing a customized focus method for my webpage using the following script: <script type="text/javascript"> function myFunction() { document.getElementById("name").focus(); } </script> I ...

Is it possible to maintain HTML, JS, and CSS files as separate entities when developing Vue.js components, similar to how it is

Is it possible to maintain separate HTML, JS, and CSS files while creating Vue.js components? I recently read the "Why Vue.js doesn't support templateURL" article which discusses this topic. "Proper modularization is a necessity if you want to bu ...

Tips for retrieving multiple values or an array from an AJAX request?

Is there a correct way to pass multiple sets (strings) of data back after executing an ajax call in php? I understand that echo is typically used to send a single string of data back, but what if I need to send multiple strings? And how should I handle th ...

Replicate the preceding input data by simply clicking a button

Here is some HTML and jQuery code that I am working with: $(".btn-copy").click(function() { var previousContent = $(this).prev()[0]; previousContent.select(); document.execCommand('copy'); }); <script src="https://cdnjs.cloudflare.com ...

$.ajax causing a JSON input string malfunction

My web API requires the following JSON format for input: [{ "atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe", "atrSpaClassLegendId": "00D18EECC47E7DF44200011302", "atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"}, { "atrSpaUserId": "47 ...

Tips for modifying the default settings of a CSS framework like Material UI

Exploring the realm of CSS for the first time and feeling a bit lost. I am working with material ui alongside react and redux. My goal is to customize certain properties of a specific component, such as TextField with the disabled attribute. Upon inspectin ...

VSCODE's intellisense feature seems to be ignoring CSS code within JSX files

I've been puzzling over why Visual Studio Code isn't recognizing CSS syntax inside JSX files. While I'm typing, CSS IntelliSense doesn't provide suggestions for CSS - only Emmet suggestions.https://i.stack.imgur.com/FegYO.png Despite t ...

What are the best practices for implementing the CSS id selector?

As someone new to web development, I am facing an issue with my code where the CSS id selector is not functioning as expected: li { border: 3px solid red; } h3 { background: green; } #special { color: green; } <h3>Todo List</h3> < ...

Does JSON.Stringify() change the value of large numbers?

My WCF service operation returns an object with properties of type long and List<string>. When testing the operation in a WCF application, everything functions correctly and the values are accurate. However, when attempting to call the service using ...

I'm having trouble with my AJAX Update Panel. Can someone please help me figure out what I'm doing wrong?

--------------Handling Gridviews DataBound Event ----------------- protected void grdShowCallingList_DataBound(object sender, EventArgs e) { if (grdShowCallingList.Rows.Count > 0) { foreach (GridViewRow row in grdShowCallingList.Rows) ...

Extract all objects from an array where a specific field contains an array

data:[ { id:1, tags:['TagA','TagB','TagC'] }, { id:2, tags:['TagB','TagD'] }, { id:3, tags:[&a ...

Ways to verify if the CSS background-color is set to white?

I am looking for a solution: $('*').click(function() { if($(this).css("background-color") == "#ffffff") { $(this).css("background-color") == "#000000" } });​​​​ that will execute on click of a specific cla ...

Having trouble getting static serving to work on Express.js when custom middleware is added

Seeking assistance with creating a middleware for my express js website to incorporate subdomains and serve static image, css, and js files. While my HTML pages load properly, I encounter long page load times and the javascript files fail to load. Any gui ...

The issue of Bootstrap dynamic tabs retaining their active state even after switching tabs, leading to elements being stacked

For my university project, I am developing a website that resembles a text editor using Bootstrap as the framework. To create the website menus, dynamic tabs have been utilized. The following is the code snippet I have implemented: <!--Bootstrap ...

How can one transform a json object into a json string and leverage its functionalities?

I recently encountered an issue with a JSON object that contains a function: var thread = { title: "my title", delete: function() { alert("deleted"); } }; thread.delete(); // alerted "deleted" thread_json = JSON.encode(thread); // co ...

I am looking to serve static HTML files in Express.js while also retaining app.get() methods for handling server-side logic

It may sound trivial, but I am struggling with displaying HTML files within app.get() methods using Express. Most solutions I have found involve using app.use(express.static(__dirname + '/public'));, which limits server-side logic. What I want i ...

I'm struggling with my project called "Number TSP" and I can't seem to figure out why it's not working properly

Upon reaching the end of my code, I am encountering an issue where instead of seeing the expected output of "Done!", it displays undefined. This is the code in question: const container = document.querySelector(".container") const table = document.querySe ...