Getting orthographic camera to match canvas pixels

Hi, first time posting a question, probably be many more. I am currently trying to setup an orthographic camera that matches the canvas size - so a 100x100 plane will be 100x100 pixels on screen.

I’ve searched everywhere for this, I would have thought it would be easy, but it doesn’t seem to be working.

Is there any trick to this?

1 Like

Hi @joelutting and welcome to the forum

by setting camera to ortho and with appropriate ortho left/right/top/bottom, you can match pixel.
For example in this PG:

https://playground.babylonjs.com/#NCQNCM

if the canvas is 100pixel wide, 1 world unit will be 1 pixel.

2 Likes

yeah a bit confused by that answer. I actually already do this but it doesn’t seem to work.

I take the canvas size and set the ortho top etc to - and + half that size - so 0,0 would be the centre of screen. And then I create a plane 100x100 in size. But it is not 100x100 pixels in size on screen.

Never really used the playground so not sure how it works to demonstrate this.

do you have a link to your test?

Messed around with playground and finally got an example to work - then it seemed to work fine in playground. Finally figured out the problem with my code - all good now.

This was the code;

var createScene = function() {

var scene = new BABYLON.Scene(engine);

scene.ambientColor = new BABYLON.Color3(1, 1, 1);

var camera = new BABYLON.ArcRotateCamera('Camera',Math.PI / 2, Math.PI / 2, 100, BABYLON.Vector3.Zero(), this.Scene);

var rect = engine.getRenderingCanvasClientRect();

var hw = rect.width/2;

var hh = rect.height/2;

console.log(rect.width);



camera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;    



camera.orthoLeft = -hw;

camera.orthoRight = hw;

camera.orthoBottom = hh;

camera.orthoTop = -hh;

// This targets the camera to scene origin

camera.setTarget(BABYLON.Vector3.Zero());

// This attaches the camera to the canvas

camera.attachControl(canvas, true);

var myMaterial = new BABYLON.StandardMaterial("myMaterial", scene);

myMaterial.diffuseColor = new BABYLON.Color3(1, 0, 1);      



  const plane = BABYLON.MeshBuilder.CreatePlane("plane", {width:100, height:100, sideOrientation: BABYLON.Mesh.DOUBLESIDE}, scene);

  plane.material = myMaterial;

return scene;

};

2 Likes

hello,

I made this PG before seeing your question, there is a function who calulate the ortho values to match the canvas size, maybe it can help you.

have a good day.

4 Likes