user291701
user291701

Reputation: 39681

How to get the width/height of a Canvas?

I'd like to have a canvas on my html page, with width = 100%. I'd like to then get the width in pixels of the canvas at runtime. Something like:

Canvas c = Canvas.createIfSupported();
c.setWidth("100%");
c.setHeight("100%");

// let's draw a rectangle to fill the whole canvas:
c.getContext2d().rect(0, 0, ?, ?); // <-- what's its actual width/height?

Thanks

Upvotes: 3

Views: 3457

Answers (2)

Chris Lercher
Chris Lercher

Reputation: 37778

It's (surprisingly)

c.getContext2d().rect(0, 0, 299, 149);

... no matter what the actual pixel size of the canvas is. The reason is, that 300x150 is the default coordinate space size, see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-element

You can change this by using canvas.setCoordinateSpaceWidth() and canvas.setCoordinateSpaceHeight() to anything you want.

Often, people want to draw independently of the actual size of the canvas, so they just set the coordinate space to something like 100x100, and the drawn image gets scaled automatically.

However, you may want to find out about the actual canvas pixel size:

Scheduler.get().scheduleDeferred(new ScheduledCommand() {

  @Override
  public void execute() {

    final int clientWidth = canvas.getElement().getClientWidth();
    final int clientHeight = canvas.getElement().getClientHeight();

    setupCoordinateSpace(canvas, clientWidth, clientHeight);
    drawMyImage(canvas);
  }
});

Note, that this must be done in scheduleDeferred, because the client size will only be known after the browser had a chance to perform the layout.

You can use this information to adjust the aspect ratio to match the canvas (which I would recommend, because otherwise you get distorted images)

void setupCoordinateSpace(Canvas canvas, int clientWidth, int clientHeight) {
  final double aspect = (double) clientWidth / (double) clientHeight;
  canvas.setCoordinateSpaceHeight(
      (int) (myCoordinateSpaceWidth / aspect));
}

Or, alternatively, you can also set the coordinate space to match the pixel size, so you can perform pixel-exact drawing on an HTML5 canvas:

void setupCoordinateSpace(Canvas canvas, int clientWidth, int clientHeight) {
  canvas.setCoordinateSpaceWidth(clientWidth);
  canvas.setCoordinateSpaceHeight(clientHeight);
}

After the coordinate space has been set up, you can call drawMyImage()

Upvotes: 3

Shivam Shah
Shivam Shah

Reputation: 524

use canvas width and height methods

var width = c.width;
var height = c.height;

Upvotes: 0

Related Questions