Search code examples
gwthtml5-canvas

How to draw an ellipse in GWT?


There is no context2d.ellipse in GWT, so how can I draw an ellipse? The underlying HTML5 canvas supports it, so I thought I would try and access that using a native method using the following (but it does not work)...

ellipse(context.getCanvas(),(double)x,(double)y,50.,80.,0.,0.,Math.PI*2);

...

public final native void ellipse(CanvasElement e, double x, double y, double rx, double ry, double ro, double sa, double ea)
    /*-{
        e.getContext("2d").ellipse(x, y, rx, ry, ro, sa, ea, false);
    }-*/;

ideas / solutions?


Solution

  • If there is no implementation you can draw it using lines, just needs a bit of trigonometry...

    function drawEllipse(x, y, rx, ry) {
      ctx.beginPath();
      for (i = 0; i <= 360; i++) {
        a = i * Math.PI / 180
        px = rx * Math.sin(a) + x
        py = ry * Math.cos(a) + y
        ctx.lineTo(px, py);
      }
      ctx.stroke();
    }
    
    var canvas = document.querySelector('canvas');
    var ctx = canvas.getContext('2d');
    
    drawEllipse(100, 100, 90, 30);
    drawEllipse(100, 100, 50, 90);
    drawEllipse(100, 100, 50, 25);
    <canvas id=canvas width=200 height=200></canvas>