^wasd controls enabled^
So, why would you want to use a canvas as a texture? Well, It basically makes it so you have a 3D canvas that you can control as easily as a regular canvas. This allows you to make things like screens, signs, heads-up displays, and literally anything else.
Getting started
Here is the code for the example above, we are going to take it apart and I’ll tell you exactly how it works:
<script src="https://aframe.io/releases/0.8.0/aframe.min.js"></script> <script type="text/javascript"> AFRAME.registerComponent('start',{ init: function(){ this.canvas = document.getElementById('canvas'); this.ctx = canvas.getContext("2d"); console.log("somethig should be happening!"); console.log(this.canvas); console.log(this.ctx); this.ctx.beginPath(); this.ctx.rect(20, 20, 150, 100); this.ctx.fillStyle = "red"; this.ctx.fill(); this.ctx.beginPath(); this.ctx.rect(40, 40, 150, 100); this.ctx.fillStyle = "blue"; this.ctx.fill(); } }); </script> <a-scene embedded style="height: 300px;width: 600px;" start> <a-assets> <canvas id="canvas"></canvas> </a-assets> <a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" material="src:#canvas"></a-plane> <a-box position="-1 0.5 -3" rotation="0 45 0" material="src:#canvas" ></a-box> <a-sphere position="0 1.25 -5" radius="1.25" material="src:#canvas" ></a-sphere> <a-cylinder position="1 0.75 -3" radius="0.5" height="1.5" material="src:#canvas" ></a-cylinder> <a-sky color="#ECECEC"></a-sky> <camera wasd-controls position="0 1.6 0"></camera> </a-scene>
It’s actually a lot simpler then it seems.
First, you create a canvas, but you have to make sure to put it inside an a-assets tab. This makes sure that it will not be displayed and allows Aframe to use it as an asset.
<a-assets> <canvas id="canvasId"></canvas> </a-assets>
Then, to use it as a texture you just set the material component to use it as a texture like this:
material="src:#canvasId"
And you are done. Just like that. That is unless you want to draw to your canvas. To draw to our canvas we are going to use an Aframe component, we do this so our code runs after Aframe has loaded:
AFRAME.registerComponent('start',{ init: function(){ this.canvas = document.getElementById('canvas'); this.ctx = canvas.getContext("2d"); console.log("somethig should be happening!"); console.log(this.canvas); console.log(this.ctx); this.ctx.beginPath(); this.ctx.rect(20, 20, 150, 100); this.ctx.fillStyle = "red"; this.ctx.fill(); this.ctx.beginPath(); this.ctx.rect(40, 40, 150, 100); this.ctx.fillStyle = "blue"; this.ctx.fill(); } });
Then we use it by putting it in any aframe tag like this:
<a-scene start>
Something to note is that Aframe automaticly updates the texture whenever you update the canvas so you don’t have to worry about that.
And there you go! You can now use a fully functional canvas as a texture for your Aframe objects.