0

I am starting out with Three.JS and simply trying to render a sprite. However, I haven't been able to get a basic sprite to render. In my example below, I have a simple 200x200 canvas which I am attempting to fill with a 200x200 sprite on the screen, and allow the upper left to be the 0,0 point, instead of the center. But the (red) sprite never shows up -- instead only the yellow background. Can sprites be independently rendered, or do they need to be associated with something else? I was unable to find a basic working example of just a sprite being rendered.

https://jsfiddle.net/CodeVirtue/4wv8tj57/

const canvas = document.getElementById('main');
const body = document.getElementById('body');

const w = 100;
const h = 100;

const scene = new THREE.Scene();
const camera = new THREE.OrthographicCamera(0, 0, w, h, 0, 1000);
const renderer = new THREE.WebGLRenderer({canvas});

scene.background = new THREE.Color(0xffff00);
renderer.setSize(w, h);
const sprite = createSprite(w, h);
scene.add(sprite);
camera.lookAt(w / 2, h / 2, 0);

function createSprite(w, h) {
  const material = new THREE.SpriteMaterial({ color: 0xff0000 });
  const sprite = new THREE.Sprite(material);
  sprite.position.set(w / 2, h / 2, 0);
  sprite.scale.set(w, h, 1);
  return sprite;
}

function animate() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
}
animate();
body {
  margin: 0;
  padding: 0;
  border: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.js"></script>
<body id="body">
  <canvas id="main"></canvas>  
</body>
WestLangley
  • 102,557
  • 10
  • 276
  • 276
Agendum
  • 1,697
  • 1
  • 18
  • 36
  • See [how to instantiate an orthographic camera](https://stackoverflow.com/a/17567292/1461008). – WestLangley Mar 18 '23 at 01:52
  • Your ortho camera has no width, since its left and right edges are both at 0. See the docs on how to initialize an ortho camera: https://threejs.org/docs/index.html?q=ortho#api/en/cameras/OrthographicCamera – M - Mar 18 '23 at 06:50
  • Thanks, I am still learning all of this, and that led me to realize I can never think of this in terms of window coordinates. That is because there isn't a "width" and "height" of the sprite that I traditionally think of, only a scale, and it stretches out from the center, not the upper left. So no matter what I do with the camera, the sprite positioning will need to have some math done to convert coordinate positions to account for different form of sizing in WebGL world. Thanks! – Agendum Mar 18 '23 at 21:42

0 Answers0