0

When I try to load getContext function in javascript I have to use the window.load function to first load the DOM object before running my javascipt code. So my question is if there is any other way to run the getContext function without having to put all my code in a function,and without using other type a library. Here's is my code.

function init() {
    var cvs = document.getElementById("myCanvas"); 
    var ctx = cvs.getContext("2d");
    ctx.rect(20,20,150,100);
    ctx.stroke(); 
}

window.onload = init;
In here I want to use ctx.rect, and ctx.stroke to be outside my function.
  • 4
    Put your ` – Marty Apr 11 '18 at 03:33
  • Where is the `getContext` function? What does it do? If you are accessing the DOM. You will need to wait until the elements are loaded. Also, How when exactly would you like to run the script? – nipuna-g Apr 11 '18 at 03:34
  • 1
    @nipuna777 [`HTMLCanvasElement.getContext()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext) – Phil Apr 11 '18 at 03:51

2 Answers2

0

You can also put your script at the bottom of the HTML.

<div id="someid"></div>
<script>
  console.log(document.querySelector('#someid'));
</script>

You can also ensure that the script is in a separate file and use defer:

<head>
<script src="myscript.js" defer></script>
</head>
<body>
<div id="someid"></div>

defer will make the script automatically run only after the document is loaded, so I think it's the best method. Also, since scripts are information about how to interact with the content rather than being content themselves, I think they semantically belong in the header rather than at the end of the body. (While you can put a script at the end of the body to ensure the body is populated before the script runs, I don't think that's a very clean way of doing things)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

You need to make sure that your js runs after your DOM is populated with the canvas tag, or else it will not be there when the JS is looking for it.

One way to do this is as you have done already. This may be the best way of all. But I would write it like this:

window.addEventListener("load", init);

There is nothing at all wrong with this, and you should be in the habit of putting all of your code in functions anyway. But there are other options.

You can put the defer attribute in your script tag. This will make it run after the DOM loads.

Or you can put your script tag in a place after your canvas tag. The place the script tag appears in the HTML determines when it executes. So you can put it at the end of the body.

jojois74
  • 795
  • 5
  • 10