[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 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 New Member

    Joined:
    Oct 16, 2016
    Messages:
    33
    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 New Member

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

Share This Page

  • About Indie Gamer

    When the original Dexterity Forums closed in 2004, Indie Gamer was born and a diverse community has grown out of a passion for creating great games. Here you will find over 10 years of in-depth discussion on game design, the business of game development, and marketing/sales. Indie Gamer also provides a friendly place to meet up with other Developers, Artists, Composers and Writers.
  • Buy us a beer!

    Indie Gamer is delicately held together by a single poor bastard who thankfully gets help from various community volunteers. If you frequent this site or have found value in something you've learned here, help keep the site running by donating a few dollars (for beer of course)!

    Sure, I'll Buy You a Beer