User Interaction in WebGL

Duncan Murdoch

August 25, 2016

Introduction

This document describes how to embed rgl scenes in HTML documents and use embedded Javascript to control a WebGL display in an HTML document. For more general information, see rgl Overview.

We assume that the HTML document is produced from R markdown source using knitr or rmarkdown. This format mixes text with Markdown markup with chunks of R code.

There are two ways to embed an rgl scene in the document. The older one is to use the chunk option webgl = TRUE. With that option, whatever rgl scene is active at the end of the chunk will be embedded. See the setupKnitr help page.

The second way is to use a call to rglwidget. Each call to this function will insert a scene into the document. Do not set webgl = TRUE.

The second method is easier for me to maintain, so it is likely to receive more support in the future, but for now both methods are supported, and there are examples of both in this document.

I am currently conducting experiments on a third method. This is intended to be similar to the way standard 2D graphics are included by knitr, i.e. it will detect the fact that you’ve drawn something, and just include it automatically.

Browser support

Most browsers now support WebGL, but it may be disabled by default. See http://get.webgl.org for help on a number of different browsers.

If you are using the internal browser in RStudio, support varies by version. I believe it is enabled by default in Windows versions, but until recently was not enabled in Mac OSX versions. You can run this command in Terminal:

defaults write org.rstudio.RStudio WebKitWebGLEnabled -bool YES

to enable it. I do not have much experience with RStudio in Linux, but it does seem that WebGL is enabled there.

Examples

We start with two simple examples. The next section gives reference information.

Consider the simple plot of the iris data. We insert a code chunk and call the rglwidget function with optional argument elementId. This allows later Javascript code to refer to the image.

library(rgl)
with(iris, plot3d(Sepal.Length, Sepal.Width, Petal.Length, 
                  type="s", col=as.numeric(Species)))
subid <- currentSubscene3d()
rglwidget(elementId="plot3drgl")