How can I put a Regl/WebGL canvas into a HTML div container

516 Views Asked by At

I'm very new to web design/javascript etc so please forgive rookie level knowledge.

I'm developing some data visualisations using Regl to show a high volume of points on screen using the fantastic work of Jim Vallandingham and Peter Beshai as a starting point. I've used D3.js a little so was hoping to use this in a similar way.

I have been able to generate the Regl/webGL visualisation as a full screen canvas with no issues, but what I would like to do next is put the canvas into a html container (in the same way that a D3.js SVG can be inserted into a container) so that I can surround with html text etc. Ultimately I'd like to try and build a scrollytelling piece incorporating this viz.

So in the example below I'd like the Regl/webGL canvas to be attached to the "div" html container and resized to fit the 400x300px dimensions. I've got no idea how to do it though as there is no command to attached the canvas to a html element as per D3.

Can anyone help? Thanks in advance

HTML:

<!DOCTYPE html>
<script src="https://npmcdn.com/[email protected]/dist/regl.js"></script>
<div id="div" width="400" height="300"></div>

JS:

var regl = createREGL();

var drawTriangle = regl({

  // fragment shader
  frag: `
precision mediump float;
uniform vec4 color;
void main () {
gl_FragColor = color;
}`,

  // vertex shader
  vert: `
precision mediump float;
attribute vec2 position;
void main () {
gl_Position = vec4(position, 0, 1);
}`,

  // attributes
  attributes: {
    position: [
      [-1, 0],
      [0, -1],
      [1, 1]
    ]
  },

  // uniforms
  uniforms: {
    color: [1, 0, 0, 1]
  },

  // vertex count
  count: 3
})

drawTriangle();

myFiddle: https://jsfiddle.net/joe_wretham/26xrw3pL/2/

1

There are 1 best solutions below

0
On

I'm sorry it took so long for someone to answer your question! Here's how to run Regl in a browser canvas, with a simple example of an html and javascript file.

basic.html

<!DOCTYPE html>
<title>Simple regl Triangle Example in Canvas</title>


<body style="background-color:black;">
  <br><br><br>
 <center> <canvas id="myCanvas" width="400" height="400"></canvas> </center>

  <script src="https://npmcdn.com/[email protected]/dist/regl.js"></script>
  <script src="basic.js"></script>

</body>

basic.js

var regl = createREGL(document.getElementById('myCanvas'));

var drawTriangle = regl({

  // fragment shader
  frag: `
  precision mediump float;
  uniform vec4 color;
  void main () {
    gl_FragColor = color;
  }`,

  // vertex shader
  vert: `
  precision mediump float;
  attribute vec2 position;
  void main () {
    gl_Position = vec4(position, 0, 1);
  }`,

  // attributes
  attributes: {
    position: [
      [-1, 0],
      [0, -1],
      [1, 1]
    ]
  },

  // uniforms
  uniforms: {
    color: [1, 0, 0, 1]
  },

  // vertex count
  count: 3
})
regl.clear({color:[1,1,1,1]})
drawTriangle();

browser output:

enter image description here