Caleb Jay
Caleb Jay

Reputation: 2199

Positioning on an HTML5 Canvas

I'm confused about the coordinate system on the HTML5 canvas. I've created a 500x500 canvas and as per this answer I've tried to orient it in a more understandable Cartesian format. However, I'm getting unexpected behavior with my orange square.

With a canvas of 500,500, I would expect a fillRect(-250,-250,100,100) to have a top-left corner in the top-left of the canvas, but instead it's nowhere to be found. For some reason, a fillRect(150,150,100,100) has a top-right corner in the top-right of the canvas.

I'm hopelessly confused, can someone shed light on the dynamics of the HTML5 canvas?

drawanimation.html:

    <!DOCTYPE html>
<html>
<head>
  <title>Animate Something!</title>
  <link rel='stylesheet' href='drawanimation.css'></link>
  <script src='drawanimation.js'></script>
</head>
<body onload = "draw();">
<canvas id="drawer" width="500" height="500"></canvas>
</body>
</html>

drawanimation.js

var width = 500;
var height = 500;

var draw = function(){

  var canvas = document.getElementById('drawer');
  var context = canvas.getContext('2d');
  context.save();
  context.clearRect(0,0,width,height);
  context.translate(width/2,height/2); //cartesian attempt
  //context.rotate(-Math.PI/2); //spin this thing until it's oriented right!
  context.fillStyle = 'orange';
  context.fillRect(150, 150 ,100,100);
  context.restore();
};

Upvotes: 1

Views: 1015

Answers (1)

Blindman67
Blindman67

Reputation: 54109

The Cartesian coordinate system does not define the direction of the axis.

The adopted standard for computer graphics is the origin in the top left corner with the X axis across the top from left to right and the y axis down the screen from top to bottom.

This is generally because in days past indexing into the display memory matched the CRT scan line order with the first byte read at the lowest address.

Though this does not hold with modern computers as all render calls are first transformed. You can set the origin where ever you wish and the direction of the axis which ever way you want.

If you want the y axis to go from bottom left up and the x axis to go from the bottom left across right then set the transform to ctx.setTransform(1,0,0,-1,0,499)

The first 2 numbers are the direction and scale of a pixel of the X axis, the second are the direction and scale of pixels for the y axis, and the last two numbers are the location of the origin in absolute pixel address.

So if you want the origin in the bottom right and x from right to left and y from bottom to top then ctx.setTransform(-1,0,0,-1,499,499) but you will still have to draw the object in the positive coordinates.

Or for the math system with y up and x going left to right with the origin in the center of the canvas ctx.setTransform(1,0,0,-1,250,250)

Upvotes: 5

Related Questions