1

I am trying to draw a bar in the center of a canvas. I would expect the bar to be centered horizontally, but it is only padded sligthly to the left. What is wrong?

CSS:

#my-canvas {
    border: 1px solid #ffffff;
    height: 100px;
    width: 100px;
}

HTML:

<canvas id="my-canvas"></canvas>

JavaScript:

var bar = document.getElementById("my-canvas");
var barContext = rejectedBar.getContext("2d");

var canvasWidth = bar.scrollWidth;
var canvasHorizontalCenter = canvasWidth / 2;
var canvasHeight = bar.scrollHeight;
var barWidth = 50;
var barHorizontalCenter = barWidth / 2;

barContext.fillStyle = "#781108";
barContext.fillRect(canvasHorizontalCenter - barHorizontalCenter, 0, barWidth, 100);
LuckyLuke
  • 47,771
  • 85
  • 270
  • 434

1 Answers1

4

Making your canvas be 100 pixels wide via CSS does not affect the conceptual width of the canvas for drawing purposes. To set that you can use the "width" and "height" properties on the canvas tag.

<canvas width=100 height=100></canvas>

If you don't specify that, the default is 300 wide by 150 high.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 1
    To add, you could draw on the canvas, *then* apply a class that changes the dimensions and the canvas will scale much as an `img` tag would. – Marc Aug 20 '13 at 19:40