COMMUNITY

Help getting started with drawing on html canvas

Would like to get the skeleton together for using Haxe to draw on an html canvas.

My Main.hx file:

import js.Browser;

class Main {
    public static function main() {
        var canvas = Browser.document.getElementById("myCanvas");
        var context = canvas.getContext("2d");
        context.moveTo(20, 40);
        context.lineTo(200, 100);
        context.stroke();
    }
}

and the error I’m getting:

src/Main.hx:6: characters 30-40 : js.html.Element has no field getContext (Suggestion: textContent)

My index.html body looks like:

  <body>
    <h1>Hi</h1>
    <p>Hi there, you!</p>

    <canvas id="myCanvas" style="border:2px solid RoyalBlue;" width="500" height="300"></canvas>

    <script src="scripts/main.js"></script>
  </body>

How should my Main.hx code look to start drawing?

Thanks!

getElementById() returns a generic js.html.Element, while you want to work with a canvas element. You need to cast it:

var canvas:CanvasElement = cast Browser.document.getElementById("myCanvas");
1 Like

You can do var context = canvas.getContext2d(); to get the context typed as CanvasRenderingContext2D :smile:

1 Like

Ah, thank you! Works now. Also, I had to put a

import js.html.CanvasElement;

at the top.

Thanks, Mark! Had not run into that yet, but it looks like it saves me a cast.