1

What is the correct way to style an HTML canvas element via a function that takes any style rule and value as parameters? Yes I know a direct Javascript approach would work. The setCSS() function is a testbed for a version 2 setCSS() function that is intended to set multiple css styles by utilizing an array of objects (key, values) as parameters such that each object represents a single CSS property. Here is what I have that is not working:

    function init() {
        'use strict';
        let can = document.getElementById('canvas');
        let ctx = canvas.getContext('2d');
        resizeBlock(can, 50, 50);
 // Tried both forms individually by commenting out other function
        setCSS(can, 'borderWidth', '20px');// not working
        setCSS(can, 'borderWidth', '20');// not working
    }

    function setCSS(element, rule, value) {
        element.style.rule = value;
        return element; // should element return or not?
    }
Jules Manson
  • 214
  • 2
  • 13
  • 4
    `window.onload = init;` without parenthesis. – ibrahim mahrir Jun 23 '17 at 17:16
  • 2
    In you example: `window.onload = init();` is the same as: `window.onload = undefined` because the execution of `init` yields `undefined` (doesn't return anything). Instead you should not execute the function, just pass a reference to it so it can be called when the window loads. – ibrahim mahrir Jun 23 '17 at 17:17
  • 1
    even if you follow the upper examples, it wont work as window.onload is overriden by your second function. – Jonas Wilms Jun 23 '17 at 17:18
  • 1
    Possible duplicate of [pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it](https://stackoverflow.com/questions/9899372/pure-javascript-equivalent-to-jquerys-ready-how-to-call-a-function-when-the) – Schlumpf Jun 23 '17 at 17:19
  • 2
    @Jonasw The functions are the same, OP is just asking why the second one works and the first not. He didn't mean to have two load events. – ibrahim mahrir Jun 23 '17 at 17:20

1 Answers1

1

init is the function, init() is the result of calling the function.

So this would work:

window.onload = init;

Also you may want to put it after defining the init() function.

function init() { ...snip... }
window.onload = init;
Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156