[Javascript] I need help setting up the canvas element in HTML5

Discussion in 'Game Development (Technical)' started by caleb.bertrand, Nov 29, 2016.

  1. caleb.bertrand

    caleb.bertrand
    Expand Collapse
    New Member

    Joined:
    Oct 18, 2016
    Messages:
    4
    Likes Received:
    0
    I've been learning Javascript for a few years, but only in an editor like the one on Khan Acadamy. Now I'm working on sublime text, I have found out you need a <canvas> element to work with it. I know you can do stuff like this:

    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.moveTo(0,0);
    ctx.lineTo(200,100);
    ctx.stroke();

    But I don't want to have to write "ctx" before all my commands. Is there a way I can set up the canvas to where I can just write "ellipse()" and "rect()" like a normal person and it works? If possible, I'd like to do this without a library. Thank you so much!
     
  2. WildG

    WildG
    Expand Collapse
    New Member

    Joined:
    Oct 16, 2016
    Messages:
    19
    Likes Received:
    0
    Only way I see how is to put your ctx in a global variable. Using your code:

    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");

    function Line() {

    ctx.moveTo(0,0);
    ctx.lineTo(200,100);
    ctx.stroke();

    }

    Line();


    Good enuf?
     
  3. WildG

    WildG
    Expand Collapse
    New Member

    Joined:
    Oct 16, 2016
    Messages:
    19
    Likes Received:
    0
    Not really a global variable but you get what I mean...
     

Share This Page