View Single Post
Default   #62   Coda Coda is offline
Developer
Using the "onload" attribute like that is old-school Javascript and while it's still supported it's not recommended because it has a LOT of limitations.

<script> tags get executed immediately, as soon as they're encountered by the browser, before the rest of the page is allowed to load. This is true even if the script has to be loaded from another URL, in contrast to CSS files in a <link> attribute, which are loaded in the background.

The "load" event (which is what causes the "onload" attribute to execute) happens when all content on the page is finished loading. If you don't actually NEED all of the content on the page to have finished loading, you can just put your <script> tag near the bottom of the file and all of the document above it (but not necessarily CSS files or images) is guaranteed to already be ready.

If you DO need to wait for the "load" event (for example, if you want to work with image files, like you described) then the recommended way to do it is like this:

Code:
document.body.addEventListener('load', aasdf);
Notice that there's no () on "aasdf" there; this is intentional -- you aren't invoking the function; you're passing the function AS AN OBJECT to the addEventListener method, which will invoke it when the "load" event is triggered.

As for actually drawing images, it's not too hard. Put the image you want in an <img> tag on the page (you can hide it with CSS if you want), grab it from the page with "document.getElementById", and draw it to the canvas using "drawImage".

The code might look something like this:

Code:
<img src='example.png' id='exampleImage' />
<canvas id='workCanvas' />
<script type='text/javascript'>
function startup() {
  var context = document.getElementById('workCanvas').getContext('2d');
  var imgData = document.getElementById('exampleImage');
  context.drawImage(imgData, 10, 10);
}
document.body.addEventListener('load', startup);
</script>
Games by Coda (updated 4/8/2025 - New game: Marianas Miner)
Art by Coda (updated 8/25/2022 - beatBitten and All-Nighter Simulator)

Mega Man: The Light of Will (Mega Man / Green Lantern crossover: In the lead-up to the events of Mega Man 2, Dr. Wily has discovered emotional light technology. How will his creations change how humankind thinks about artificial intelligence? Sadly abandoned. Sufficient Velocity x-post)
Old Posted 01-03-2017, 11:28 PM Reply With Quote