Skip to content

Commit

Permalink
Fix flicker and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
David Emanuel Luksic committed May 4, 2020
1 parent 59e6784 commit 2fcb879
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 4 deletions.
66 changes: 66 additions & 0 deletions example/dynamic-resize.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
tags: resizing
<p> This example is a demonstration of automatic resizing when rendering into a div that dynamically changes its size. </p>
<p> NOTE: this will only work if your browser supports ResizeObserver. Otherwise it falls back to detecting window resizes. </p>
*/

// Lets inject into a div that is resized dynamically
const div = document.createElement('div')
div.style.width = '100%'
div.style.height = '100vh'
document.body.appendChild(div)
document.body.style.margin = '0'

const regl = require('../regl')({
container: div
})

const drawcmd = regl({

// In a draw call, we can pass the shader source code to regl
frag: `
precision mediump float;
uniform vec4 color;
void main () {
gl_FragColor = color;
}`,

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

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

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

count: 3
})

function draw () {
regl.poll()
regl.clear({
color: [0, 0, 0, 1],
depth: 1
})
drawcmd()
}

regl.frame(() => draw())

// on mouse move make div different size
window.addEventListener('mousemove', ev => {
div.style.width = ev.clientX.toFixed(0) + 'px'
div.style.height = ev.clientY.toFixed(0) + 'px'
})
14 changes: 10 additions & 4 deletions lib/webgl.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,14 @@ function createCanvas (element, onDone, pixelRatio) {
})
}

var resizeObserver;
if (typeof ResizeObserver === 'function') {
resizeObserver = new ResizeObserver(resize)
var resizeObserver
if (element !== document.body && typeof ResizeObserver === 'function') {
// ignore 'ResizeObserver' is not defined
/* eslint-disable */
resizeObserver = new ResizeObserver(function () {
// setTimeout to avoid flicker
setTimeout(resize)
})
resizeObserver.observe(element)
} else {
window.addEventListener('resize', resize, false)
Expand All @@ -48,8 +53,9 @@ function createCanvas (element, onDone, pixelRatio) {
function onDestroy () {
if (resizeObserver) {
resizeObserver.disconnect()
} else {
window.removeEventListener('resize', resize)
}
window.removeEventListener('resize', resize)
element.removeChild(canvas)
}

Expand Down

0 comments on commit 2fcb879

Please sign in to comment.