Dimensions in html5 canvas

76 views Asked by At

I have a problem with the HTML5 Canvas. I use jCanvas to add layers to an canvas but I have a problem with the sizes.

I have 2 rectangles a green one and a red one. Now I want the red box touch the green left top corner.

Using the coordinate system I start green at coordinates 200, 200 then red has to start at 0,0 and the width and height has to be 200 and 200. But that doesn't work

Check this example

Why doesnt this work??

When I use 100x100 dimensions it does work

1

There are 1 answers

1
Benjy763 On BEST ANSWER

All depends on the origin of your layer. By default it is the center of the layer. So to have the results you expect there are two solutions (exemples with layer 100*100) :

First in your case you have to calculate correct position from top left canvas origin to the middle of your object :

$('canvas')
.addLayer({
  type: 'rectangle',
  name: 'redBox',
  fillStyle: '#c33',
  x: 50, y: 50,//canvas origin to center (100/2)
  width: 100, height: 100
})
.addLayer({
  type: 'rectangle',
  name: 'greenBox',
  fillStyle: '#585',
  x: 150, y: 150,//canvas origin to center (100 of red layer + 100/2)
  width: 100, height: 100
})
.drawLayers();

Or you can set origin to top left corner by disable fromCenter property:

$('canvas')
.addLayer({
  type: 'rectangle',
  name: 'redBox',
  fillStyle: '#c33',
  fromCenter: false,
  x: 0, y: 0,
  width: 100, height: 100
})
.addLayer({
  type: 'rectangle',
  name: 'greenBox',
  fillStyle: '#585',
  fromCenter: false,
  x: 100, y: 100,
  width: 100, height: 100
})
.drawLayers();

Hope this help