Skip to content

Commit

Permalink
Support HTML elements as textures when DOM/canvas are available (#87)
Browse files Browse the repository at this point in the history
  • Loading branch information
Benjamin-Dobell authored and mourner committed Dec 7, 2017
1 parent a57bd00 commit 412f16e
Showing 1 changed file with 40 additions and 4 deletions.
44 changes: 40 additions & 4 deletions webgl.js
Original file line number Diff line number Diff line change
Expand Up @@ -3515,6 +3515,36 @@ function checkFormat (format) {
format === gl.RGBA)
}

var extractImageData = function (pixels) {
if (typeof pixels === 'object' && typeof pixels.width !== 'undefined' && typeof pixels.height !== 'undefined') {
if (typeof pixels.data !== 'undefined') {
return pixels
}

var context = null

if (typeof pixels.getContext === 'function') {
context = pixels.getContext('2d')
} else if (typeof pixels.src !== 'undefined' && typeof document === 'object' && typeof document.createElement === 'function') {
var canvas = document.createElement('canvas')

if (typeof canvas === 'object' && typeof canvas.getContext === 'function') {
context = canvas.getContext('2d')

if (context !== null) {
context.drawImage(pixels, 0, 0)
}
}
}

if (context !== null) {
return context.getImageData(0, 0, pixels.width, pixels.height)
}
}

return null
}

var _texImage2D = gl.texImage2D
gl.texImage2D = function texImage2D (
target,
Expand All @@ -3531,9 +3561,12 @@ gl.texImage2D = function texImage2D (
type = height
format = width

if (typeof pixels !== 'object' || typeof pixels.data !== 'object') {
throw new TypeError('texImage2D(GLenum, GLint, GLenum, GLint, GLenum, GLenum, ImageData)')
pixels = extractImageData(pixels)

if (pixels == null) {
throw new TypeError('texImage2D(GLenum, GLint, GLenum, GLint, GLenum, GLenum, ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement)')
}

width = pixels.width
height = pixels.height
pixels = pixels.data
Expand Down Expand Up @@ -3646,9 +3679,12 @@ gl.texSubImage2D = function texSubImage2D (
type = height
format = width

if (typeof pixels !== 'object' || typeof pixels.data !== 'object') {
throw new TypeError('texSubImage2D(GLenum, GLint, GLint, GLint, GLenum, GLenum, ImageData)')
pixels = extractImageData(pixels)

if (pixels == null) {
throw new TypeError('texSubImage2D(GLenum, GLint, GLint, GLint, GLenum, GLenum, ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement)')
}

width = pixels.width
height = pixels.height
pixels = pixels.data
Expand Down

0 comments on commit 412f16e

Please sign in to comment.