Migrating code from Open Laszlo 3.3 to 5.0: TypeError: Error #1009: Cannot access a property or method of a null object reference - openlaszlo

I am facing the problem when i am running this code in 5.0 but it's working fine in 3.3.
I have set every thing but still it's giving the problem. Am i doing this in a wrong way?
<canvas width="1000" height="584">
<drawview width="200" height="300"
x="12"
y="12">
<handler name="onwidth">
this.redraw();
</handler>
<handler name="onheight">
this.redraw();
</handler>
<method name="redraw">
this.clear();
var roundness = 5;
this.beginPath();
this.moveTo(roundness, 0);
this.lineTo(this.width - roundness, 0);
this.quadraticCurveTo(this.width, 0, this.width, roundness);
this.lineTo(this.width, this.height - roundness);
this.quadraticCurveTo(this.width, this.height, this.width - roundness, this.height);
this.lineTo(roundness, this.height);
this.quadraticCurveTo(0, this.height, 0, this.height - roundness);
this.lineTo(0, roundness);
this.quadraticCurveTo(0, 0, roundness, 0);
this.closePath();
var g = this.createRadialGradient(-this.width * .5, -this.height *.5, .7, 1.5 * this.width, 1.5 * this.height, 0)
this.globalAlpha = 0;
g.addColorStop(0, 0x000000);
this.globalAlpha = 0.8;
g.addColorStop(1, 0xffffff);
this.setAttribute("fillStyle", g);
this.fill();
</method>
</drawview>
</canvas>

The onwidth and onheight handler are being called during the initialization of the drawview, at a point in time where the component initialization has not finished. If you check for the isinited attribute of a component, you can make sure that the redraw method is only called when the component is ready. I've added some debug output to this example to show you what's happening:
<drawview id="dv" width="100%" height="100%"
x="12"
y="12">
<attribute name="isready" value="false" type="boolean" />
<handler name="oncontext">
this.setAttribute("isready", true);
this.redraw();
</handler>
<handler name="onwidth">
Debug.write('onwidth: calling redraw()');
this.redraw();
</handler>
<handler name="onheight">
Debug.write('onheight: calling redraw()');
this.redraw();
</handler>
<method name="redraw">
Debug.info('redraw: this.ininited=' + this.isinited + ' / isready=' + this.isready);
if (this.isready) {
this.clear();
var roundness = 5;
this.beginPath();
this.moveTo(roundness, 0);
this.lineTo(this.width - roundness, 0);
this.quadraticCurveTo(this.width, 0, this.width, roundness);
this.lineTo(this.width, this.height - roundness);
this.quadraticCurveTo(this.width, this.height, this.width - roundness, this.height);
this.lineTo(roundness, this.height);
this.quadraticCurveTo(0, this.height, 0, this.height - roundness);
this.lineTo(0, roundness);
this.quadraticCurveTo(0, 0, roundness, 0);
this.closePath();
var g = this.createRadialGradient(-this.width * .5, -this.height *.5, .7, 1.5 * this.width, 1.5 * this.height, 0);
this.globalAlpha = 0;
g.addColorStop(0, 0x000000);
this.globalAlpha = 0.8;
g.addColorStop(1, 0xffffff);
this.setAttribute("fillStyle", g);
this.fill();
}
</method>
</drawview>
Edit: Updated the code support to use the oncontext event instead of isinited value
I've checked the drawview documentation, and the drawview has a special event called the oncontext event. From the docs:
The oncontext event is sent when the context is ready to use, which
can take some time in IE DHTML.
If you look at the drawview documentation in the OpenLaszlo reference, you'll see that the examples use the oncontext event handler to draw into the canvas.
I've updated my solution to use an additional attribute isready, which is set to true once the oncontext event has been received. As you can see in the debug output below, isinited is set to true before isready is set to true:
onwidth: calling redraw()
INFO: redraw: this.ininited=true / isready=false
onheight: calling redraw()
INFO: redraw: this.ininited=true / isready=false
INFO: redraw: this.ininited=true / isready=true
If you compile your code with errors for the DHTML runtime, you should have seen the following warning:
WARNING: this.context is not yet defined. Please check for the
presence of the context property before using drawing methods, and/or
register for the oncontext event to find out when the property is
available.
Unfortunately such a warning is not shown for the SWF runtime.

Related

Change control fill color while scaling object in Fabricjs

For a few days now, I have been trying to change the fill color of the control that is scaling an object.
Here is a gif of what I'm talking about:
I would like some guidance on how to achieve this. I have been digging through Fabricjs documentation for days trying to get an idea on how to approach this problem.
https://github.com/fabricjs/fabric.js/wiki/Working-with-events
My theory was to bind to mouse:down and mouse:up events. When mouse:down event fires, obtain the control context and change its fill color and when the mouse:up fires, restore the fill color.
Unfortunately, I can't find any fabricjs method that would allow me to obtain the control context.
http://fabricjs.com/docs/fabric.Canvas.html
http://fabricjs.com/docs/fabric.Object.html
canvas.on('mouse:down',(){
// Obtain control context and change fill
});
canvas.on('mouse:up',(){
// Obtain control context and restore fill
});
I'm using Fabricjs version 3.2.0
I overwrote the _drawControl from fabric.Object. As you can see I verified this.__corner control variable, If are equal I changed the fill and stroke color to red. Very important I restored the context after I drawn the control
var canvas = new fabric.Canvas('fabriccanvas');
canvas.add(new fabric.Rect({
top: 50,
left: 50 ,
width: 100,
height: 100,
fill: '#' + (0x1000000 + (Math.random()) * 0xffffff).toString(16).substr(1, 6),
//fix attributes applied for all rects
cornerStyle:"circle",
originX: 'left',
originY: 'top',
transparentCorners:false
}));
fabric.Object.prototype._drawControl = function(control, ctx, methodName, left, top, styleOverride) {
styleOverride = styleOverride || {};
if (!this.isControlVisible(control)) {
return;
}
var size = this.cornerSize, stroke = !this.transparentCorners && this.cornerStrokeColor;
switch (styleOverride.cornerStyle || this.cornerStyle) {
case 'circle':
if(control == this.__corner){
ctx.save();
ctx.strokeStyle = ctx.fillStyle='red';
}
ctx.beginPath();
ctx.arc(left + size / 2, top + size / 2, size / 2, 0, 2 * Math.PI, false);
ctx[methodName]();
if (stroke) {
ctx.stroke();
}
if(control == this.__corner){
ctx.restore();
}
break;
default:
this.transparentCorners || ctx.clearRect(left, top, size, size);
ctx[methodName + 'Rect'](left, top, size, size);
if (stroke) {
ctx.strokeRect(left, top, size, size);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.2.0/fabric.js"></script>
<br/>
<canvas id="fabriccanvas" width="600" height="200" style="border:1px solid #ccc"></canvas>

why is that gl.clear(gl.COLOR_BUFFER_BIT) and requestAnimationFrame will clear all the primitives I drew before

Hi guys I been leanring WebGL and trying to make a Tetris game out of it.
I have a couple of questions I'd like to ask:
For this game I wanted to first draw the grid as the background. However I noticed that after I drew the line, if I use gl.clear(gl.COLOR_BUFFER_BIT ); after, it will clear all the lines I drew before. I understand that gl.clear(gl.COLOR_BUFFER_BIT ); is about clearing the color buffer (and you probably will ask why I would want to do that. Just bear with me. ). Then I tried use gl.uniform4f( uColor, 0, 0, 0, 1); to send the color again to the fragment shader but it doesn't help.
The snippet is like this
window.onload = function(){
getGLContext();
initShaders();
drawLines( 0, 0, 400,400 );
gl.clear(gl.COLOR_BUFFER_BIT );
gl.uniform4f( uColor, 0, 0, 0, 1);
}
For the game I need the grid as background and I need requestAnimationFrame for the game loop and will render Tetrominos inside the loop. Therefore after drawing the line I used this draw() to draw other Tetrominos. However it removes the line I drew before. And when I comment out gl.clear(gl.COLOR_BUFFER_BIT ); inside draw(), it will remove the line along with background color.
function draw() {
gl.clear(gl.COLOR_BUFFER_BIT );
gl.drawArrays(gl.TRIANGLES, 0, index*6);
requestAnimationFrame(draw);
}
Here is the demo: https://codepen.io/zhenghaohe/pen/LqxpjB
Hope you could answer these two questions. Thanks!
This is generally the way WebGL works.
WebGL is just draws into a rectangle of pixels. There is no memory of primitives. There is no structure. There is just code and the resulting canvas which is an rectangle of pixels.
Most WebGL programs/pages clear the entire canvas every frame and redraw 100% of the things they want to show every time they draw. For tetris the general code might be something like
function render() {
clear the canvas
draw the grid
draw all the stable pieces
draw the current piece
draw the next piece
draw the effects
draw the score
}
Any knowledge of primitives or other structure is entirely up to your code.
If you want the grid lines to be static then either set a static background with CSS or use another canvas
Using a background:
const gl = document.querySelector('#c').getContext('webgl');
function render(time) {
time *= 0.001;
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
drawBlocks(gl, time);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
// --- below this line not important to the answer
function drawBlocks(gl, time) {
gl.enable(gl.SCISSOR_TEST);
const numBlocks = 5;
for (let i = 0; i < numBlocks; ++i) {
const u = i / numBlocks;
gl.clearColor(i / 5, i / 2 % 1, i / 3 % 1, 1);
const x = 150 + Math.sin(time + u * Math.PI * 2) * 130;
const y = 75 + Math.cos(time + u * Math.PI * 2) * 55;
gl.scissor(x, y, 20, 20);
gl.clear(gl.COLOR_BUFFER_BIT);
}
gl.disable(gl.SCISSOR_TEST);
}
#c {
background-image: url(https://i.imgur.com/ZCfccZh.png);
}
<canvas id="c"></canvas>
Using 2 canvases
// this is the context for the back canvas. It could also be webgl
// using a 2D context just to make the sample simpler
const ctx = document.querySelector('#back').getContext('2d');
drawGrid(ctx);
// this is the context for the front canvas
const gl = document.querySelector('#front').getContext('webgl');
function render(time) {
time *= 0.001;
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
drawBlocks(gl, time);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
// --- below this line not important to the answer
function drawBlocks(gl, time) {
gl.enable(gl.SCISSOR_TEST);
const numBlocks = 5;
for (let i = 0; i < numBlocks; ++i) {
const u = i / numBlocks;
gl.clearColor(i / 5, i / 2 % 1, i / 3 % 1, 1);
const x = 150 + Math.sin(time + u * Math.PI * 2) * 130;
const y = 75 + Math.cos(time + u * Math.PI * 2) * 55;
gl.scissor(x, y, 20, 20);
gl.clear(gl.COLOR_BUFFER_BIT);
}
gl.disable(gl.SCISSOR_TEST);
}
function drawGrid(ctx) {
// draw grid
ctx.translate(-10.5, -5.5);
ctx.beginPath();
for (let i = 0; i < 330; i += 20) {
ctx.moveTo(0, i);
ctx.lineTo(330, i);
ctx.moveTo(i, 0);
ctx.lineTo(i, 300);
}
ctx.strokeStyle = "blue";
ctx.stroke();
}
#container {
position: relative; /* required so we can position child elements */
}
#front {
position: absolute;
left: 0;
top: 0;
}
<div id="container">
<canvas id="back"></canvas>
<canvas id="front"></canvas>
</div>
As for why it clears even if you didn't call clear that's because that's whqt the spec says it's supposed to do
See: Why WebGL 'clear' draw to front buffer?

why does canvas object keep blinking during animation?

I made an animation in javascript for a house with rising smoke. the smoke is 3 functions for each part of the smoke that flow upwards from the chimney. they are controlled by a slider that toggles the speed at which the smoke exists the chimney. Everything works except when the slider is toggled left to right, the smoke blinks while rising. Could anyone tell me why that is?
Thanks
html:
<!DOCTYPE html>
<html>
<head>
<title>Carrey, Justin, Myshkin, Rost</title>
<meta charset="utf-8"/>
<link rel="stylesheet" href="style.css"/>
</head>
<body>
<canvas id="canvas" width="500" height="500">Get a new Browser!</canvas>
<script src="script.js" ></script>
<form>
<input type="range" min="10" max="250" value="100" id="speedCont"/>
<p>
Rostislav Myshkin A00787633 rmyshkin#my.bcit.ca
<br />
Completed:3-D house, smoke, animation for smoke, slider for speed.
<br />
Challanges: animating the smoke.
</p>
</form>
</body>
</html>
javascript:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.lineWidth = 4;
ctx.strokeLinecap = 'round';
var a = 1;
var speed = 100;
var posY = 100,
posY2 = 120,
posY3 = 140,
posX = 100,
vx = 5,
vy = 5;
function foundation() {
//grass
ctx.fillStyle = "green";
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.moveTo(25, 375);
ctx.lineTo(125, 325);
ctx.lineTo(471, 325);
ctx.lineTo(400, 375);
ctx.lineTo(25, 375);
ctx.fill();
ctx.stroke();
//front face ground
ctx.fillStyle = "#873600";
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.moveTo(25, 375); //top left
ctx.lineTo(25, 425); //bottom left
ctx.lineTo(400, 425); //bottom right
ctx.lineTo(400, 375); //top right
ctx.lineTo(25, 375); //top line
ctx.fill();
ctx.stroke();
//east face ground
ctx.fillStyle = "#872000";
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.moveTo(475, 325); //top right
ctx.lineTo(475, 375); //bottom right
ctx.lineTo(400, 425); //bottom line
ctx.lineTo(400, 375); //top left
ctx.lineTo(475, 325); //top right
ctx.fill();
ctx.stroke();
}
function house() {
//front face
ctx.fillStyle = "#2980B9";
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.moveTo(110, 365);
ctx.lineTo(110, 200);
ctx.lineTo(375, 200);
ctx.lineTo(375, 365);
ctx.lineTo(110, 365);
ctx.fill();
ctx.stroke();
//east face
ctx.fillStyle = "#1760B4";
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.moveTo(375, 200); //lower left
ctx.lineTo(415, 180); //
ctx.lineTo(415, 340);
ctx.lineTo(375, 365);
ctx.lineTo(375, 200);
ctx.fill();
ctx.stroke();
//roof front face
ctx.fillStyle = "#B41717";
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.moveTo(95, 210);
ctx.lineTo(160, 140);
ctx.lineTo(395, 140);
ctx.lineTo(365, 210);
ctx.lineTo(365, 210);
ctx.lineTo(95, 210);
ctx.fill();
ctx.stroke();
//roof east face
ctx.fillStyle = "darkred";
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.moveTo(365, 210);
ctx.lineTo(425, 190);
ctx.lineTo(395, 140);
ctx.lineTo(365, 210);
ctx.fill();
ctx.stroke();
//door
ctx.fillStyle = "darkred";
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.moveTo(300, 365);
ctx.lineTo(300, 295);
ctx.lineTo(250, 295);
ctx.lineTo(250, 365);
ctx.lineTo(300, 365);
ctx.fill();
ctx.stroke();
//doorknob
ctx.fillStyle = "yellow";
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.arc(290, 335, 5, 0, 2 * Math.PI, false);
ctx.fill();
ctx.stroke();
//walkway
ctx.fillStyle = "gray";
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.moveTo(250, 365); //left point
ctx.lineTo(240, 375); //left side
ctx.lineTo(290, 375);
ctx.lineTo(300, 365);
ctx.fill();
ctx.stroke();
//window living room
ctx.fillStyle = "blue";
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.moveTo(143, 347);
ctx.lineTo(143, 295);
ctx.lineTo(212, 295);
ctx.lineTo(212, 347);
ctx.lineTo(143, 347);
ctx.fill();
ctx.stroke();
//window top left
ctx.fillStyle = "blue";
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.moveTo(143, 275);
ctx.lineTo(143, 225);
ctx.lineTo(212, 225);
ctx.lineTo(212, 275);
ctx.lineTo(143, 275);
ctx.fill();
ctx.stroke();
//window top right
ctx.fillStyle = "blue";
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.moveTo(263, 275);
ctx.lineTo(263, 225);
ctx.lineTo(332, 225);
ctx.lineTo(332, 275);
ctx.lineTo(263, 275);
ctx.fill();
ctx.stroke();
//chimney front
ctx.fillStyle = "black";
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.moveTo(170, 130); //top left
ctx.lineTo(170, 180); //left side line
ctx.lineTo(200, 180); //bottom line
ctx.lineTo(200, 130); //right side line
ctx.lineTo(170, 130); //top side line
ctx.fill();
ctx.stroke();
//chimney east
ctx.fillStyle = "black";
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.moveTo(200, 130); //top left
ctx.lineTo(215, 123); //top side line
ctx.lineTo(215, 170); //right side line
ctx.lineTo(200, 180); //
ctx.fill();
ctx.stroke();
//chimney top
ctx.fillStyle = "black";
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.moveTo(170, 130); //top left
ctx.lineTo(185, 122); //left side
ctx.lineTo(210, 122); //top side
ctx.lineTo(200, 130);
ctx.fill();
ctx.stroke();
}
function smoke1(){
posY += -vy;
posX += vx;
if (posY < -15) posY = 100;
ctx.fillStyle = "aqua";
ctx.fillRect(0,0, 220, 127);
ctx.fillStyle = "rgba(0,0,0,0.5)";
ctx.beginPath();
ctx.arc(200, posY, 15, 0, Math.PI*2, true);
ctx.fill();
}
function smoke2(){
posY2 += -vy;
posX += vx;
if (posY2 < -13) posY2 = 110;
ctx.fillStyle = "rgba(0,0,0,0.5)";
ctx.beginPath();
ctx.arc(185, posY2, 10, 0, Math.PI*2, true);
ctx.fill();
}
function smoke3(){
posY3 += -vy;
posX += vx;
if (posY3 < -13) posY3 = 110;
ctx.fillStyle = "rgba(0,0,0,0.5s)";
ctx.beginPath();
ctx.arc(210, posY3, 6, 0, Math.PI*2, true);
ctx.fill();
}
function animate() {
smoke1();
var speed = document.getElementById('speedCont').value;
window.setTimeout(animate, speed);
}
function animate2() {
smoke2();
var speed = document.getElementById('speedCont').value;
window.setTimeout(animate2, speed);
}
function animate3() {
smoke3();
var speed = document.getElementById('speedCont').value;
window.setTimeout(animate3, speed);
}
/** if (a == 1) {
ctx.clearRect(0, 0, 260, 105);
smoke();
a++;
} else if (a == 2) {
ctx.clearRect(0, 0, 260, 105);
smokeMed();
a++;
} else if (a == 3) {
ctx.clearRect(0, 0, 260, 105);
smokeBig();
a = 1;
} else {
ctx.clearRect(0, 0, 260, 105);
}
window.setTimeout(animate2, speed);
}
**/
window.onload = function all() {
foundation();
house();
animate();
animate2();
animate3();
}
window.addEventListener("load", all, false);
//window.setInterval(animate2, 1000);
//window.setTimeout(animate2, speed);
css:
#canvas {
background-color: aqua;
border: 1px solid black;
margin-bottom: 10px ;
}
body {
background-color: gray;
}
input[type=range] {
-webkit-appearance: none;
border: 3px solid black;
width: 500px;
border-radius: 20px;
}
input[type=range]::-webkit-slider-runnable-track {
width: 500px;
height: 10px;
background: #ddd;
border: none;
border-radius: 20px;
}
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
border: 3px solid black;
height: 30px;
width: 30px;
border-radius: 50%;
background: red;
margin-top: -8px;
}
input[type=range]:focus {
outline: none;
}
input[type=range]:focus::-webkit-slider-runnable-track {
background: #ccc;
}
The flickr has to do with having multiple setTimeout functions. Since you delete the previous state of the smoke on smoke1(), once you change the speed there is going to be a discrepancy. If you use only one setTimeout it should work fine in your particular case. Here a JSFIDDLE as an example.
Backbuffers & requestAnimationFrame
All rendering to the DOM is double buffered. Rendering is always done to the backBuffer, it is not drawn to the screen. Presenting to the screen should be done when the scene is fully rendered.
When a function exits (returns to idle) the DOM assumes that you have completed all the rendering and what to display the results. This is when the backbuffer is moved to where the screen can see it.
If you have only rendered part of the scene and exit the DOM does not know you have not yet finished rendering and will present the backbuffer as is. The screen refreshes at a much slower rate than you can write to the backbuffer. When the DOM presents the backbuffer to the screen the display hardware may be at any point of scanning out the pixels onto the display hardware. The result is inconsistent flickering and shearing.
You can fix the problem by using only one function to do all the rendering. The problem still will be that when the function exits it may be at any point of the display scan. You will still get some shearing.
To keep in sync with the display hardware and prevent any flickering and shearing use requestAnimationFrame (there are endless answers about it in SO) to do all your rendering.
The DOM treats all callback functions called by requestAnimationFrame as special and will delay any DOM visual changes being moved from the backbuffer to the screen until the display hardware is in its vertical refresh phase. At that point all changes since the last vertical refresh are moved from back buffers to the screen. (This applies to all visual FX not just the canvas).
Fixing your code
As you want a fixed update speed.
var speed = 100;
var nextUpdateTime;
function updateAll(time){
if(nextUpdateTime=== undefined){
nextUpdateTime= time - speed; // first update now
}
if(time >= nextUpdateTime){
nextUpdateTime= time + (speed - (time - nextUpdateTime)); // get time of next update
smoke1();
smoke2();
smoke3()
}
requestAnimationFrame(updateAll);
}
requestAnimationFrame(updateAll);
If you want each FX to have its own speed you will have to create a array of speed and nextUpdateTime values. Requested animation frames generally run at 60fps. Time is always the first argument of the requested callback function.
Better yet run at 60fps
I would suggest that rather than use a slow update speed (100ms is 10fps) you modify your code to slow the animation down so that it runs smoothly when sped up to 60fps
The following will modify your animation to play the same but at a higher frame rate.
var speed = 100; // the old frame update delay
var frameRate = 60; // requestAnimationFrame frame rate
// vx and vy where the update delta move vectors for the smoke
// that need to be adjusted for the new frame rate.
vx = (vx * (1000 / speed)) / frameRate;
vy = (vy * (1000 / speed)) / frameRate;
function updateAll(time){
smoke1();
smoke2();
smoke3()
requestAnimationFrame(updateAll);
}
requestAnimationFrame(updateAll);
NOTE if you present a lot of rendering work the browser may not be able to keep up. If it cant do it in 1/60th of a second and it will not display anything until the next vertical refresh the frame rate will drop from 60fps to 30fps.
If you suspect this will happen then you should monitor the time between frames and use that to calculate the new smoke position every frame.

Multiple WebGL models on the same page

My research lab is working on a webpage that displays a long scrollable list of 3d models, about 50 or so. Our first idea was to do this with separate THREE.js WebGL contexts, but it seems this isn't advisable given the architecture of WebGL, and browsers seem to limit the number of contexts on a page to about 2^4.
I don't need these contexts to do anything very impressive: the individual geometries only have a few hundred triangles, with no textures, and only one at a time ever animates when using the mouse to rotate its camera.
Can I persuade WebGL to do what I want in a way that the browser won't complain about? I thought perhaps of having a single big geometry with all my individual models lined up next to each other, and separate canvases with viewports showing just one model each. But it seems that isn't supported. (Multiple views are allowed in the same context, but that's not very useful for me.)
Thanks for any ideas!
It's not clear why you think you need multiple webgl contexts. I'm guessing because you want a list like this
1. [img] description
description
2. [img] description
description
3. [img] description
description
Or something?
Some ideas
make one canvas big enough for the screen, set its CSS so it doesn't scroll with the rest of the page. Draw the models aligned with whatever other HTML you want that does scroll.
make an offscreen webgl canvas and use canvas2d elements to display.
For each model render the model and then call
someCanvas2DContextForElementN.drawImage(webGLcanvasElement, ...);
Given there are probably only ever a few canvases visible you only need to update those ones. In fact it's probably a good idea to recycle them. In other words, rather than make 12000 canvaes or a 12000 element list make just enough to fit on the screen and update them as you scroll.
Personally I'd probably pick #1 if my page design allowed it. Seems to work, see below.
It turned out to be really easy. I just took this sample that was drawing 100 objects and made it draw one object at a time.
After clearing the screen turn on the scissor test
gl.enable(gl.SCISSOR_TEST);
Then, for each object
// get the element that is a place holder for where we want to
// draw the object
var viewElement = obj.viewElement;
// get its position relative to the page's viewport
var rect = viewElement.getBoundingClientRect();
// check if it's offscreen. If so skip it
if (rect.bottom < 0 || rect.top > gl.canvas.clientHeight ||
rect.right < 0 || rect.left > gl.canvas.clientWidth) {
return; // it's off screen
}
// set the viewport
var width = rect.right - rect.left;
var height = rect.bottom - rect.top;
var left = rect.left;
var bottom = gl.canvas.clientHeight - rect.bottom - 1;
gl.viewport(left, bottom, width, height);
gl.scissor(left, bottom, width, height);
I'm not 100% sure if I need to add 1 the width and height or not. I suppose I should look that up.
In any case I compute a new projection matrix for every rendered object just to make the code generic. The placeholder divs could be different sizes.
Update:
the solution originally posted here used position: fixed on the canvas to keep it from scrolling. The new solution uses position: absolute and updates the transform just before rendering like this
gl.canvas.style.transform = `translateY(${window.scrollY}px)`;
With the previous solution the shapes getting re-drawn in their matching positions could lag behind the scrolling. With the new solution the canvas scrolls until we get time to update it. That means shapes might be missing for a few frames if we can't draw quick enough but it looks much better than the scrolling not matching.
The sample below is the updated solution.
"use strict";
// using twgl.js because I'm lazy
twgl.setAttributePrefix("a_");
var m4 = twgl.m4;
var gl = twgl.getWebGLContext(document.getElementById("c"));
// compiles shaders, links program, looks up locations
var programInfo = twgl.createProgramInfo(gl, ["vs", "fs"]);
// calls gl.creatBuffer, gl.bindBuffer, gl.bufferData for each shape
// for positions, normals, texcoords
var shapes = [
twgl.primitives.createCubeBufferInfo(gl, 2),
twgl.primitives.createSphereBufferInfo(gl, 1, 24, 12),
twgl.primitives.createPlaneBufferInfo(gl, 2, 2),
twgl.primitives.createTruncatedConeBufferInfo(gl, 1, 0, 2, 24, 1),
twgl.primitives.createCresentBufferInfo(gl, 1, 1, 0.5, 0.1, 24),
twgl.primitives.createCylinderBufferInfo(gl, 1, 2, 24, 2),
twgl.primitives.createDiscBufferInfo(gl, 1, 24),
twgl.primitives.createTorusBufferInfo(gl, 1, 0.4, 24, 12),
];
function rand(min, max) {
return min + Math.random() * (max - min);
}
// Shared values
var lightWorldPosition = [1, 8, -10];
var lightColor = [1, 1, 1, 1];
var camera = m4.identity();
var view = m4.identity();
var viewProjection = m4.identity();
var tex = twgl.createTexture(gl, {
min: gl.NEAREST,
mag: gl.NEAREST,
src: [
255, 255, 255, 255,
192, 192, 192, 255,
192, 192, 192, 255,
255, 255, 255, 255,
],
});
var randColor = function() {
var color = [Math.random(), Math.random(), Math.random(), 1];
color[Math.random() * 3 | 0] = 1; // make at least 1 bright
return color;
};
var objects = [];
var numObjects = 100;
var list = document.getElementById("list");
var listItemTemplate = document.getElementById("list-item-template").text;
for (var ii = 0; ii < numObjects; ++ii) {
var listElement = document.createElement("div");
listElement.innerHTML = listItemTemplate;
listElement.className = "list-item";
var viewElement = listElement.querySelector(".view");
var uniforms = {
u_lightWorldPos: lightWorldPosition,
u_lightColor: lightColor,
u_diffuseMult: randColor(),
u_specular: [1, 1, 1, 1],
u_shininess: 50,
u_specularFactor: 1,
u_diffuse: tex,
u_viewInverse: camera,
u_world: m4.identity(),
u_worldInverseTranspose: m4.identity(),
u_worldViewProjection: m4.identity(),
};
objects.push({
ySpeed: rand(0.1, 0.3),
zSpeed: rand(0.1, 0.3),
uniforms: uniforms,
viewElement: viewElement,
programInfo: programInfo,
bufferInfo: shapes[ii % shapes.length],
});
list.appendChild(listElement);
}
var showRenderingArea = false;
function render(time) {
time *= 0.001;
twgl.resizeCanvasToDisplaySize(gl.canvas);
gl.canvas.style.transform = `translateY(${window.scrollY}px)`;
gl.enable(gl.DEPTH_TEST);
gl.disable(gl.SCISSOR_TEST);
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.enable(gl.SCISSOR_TEST);
if (showRenderingArea) {
gl.clearColor(0, 0, 1, 1);
}
var eye = [0, 0, -8];
var target = [0, 0, 0];
var up = [0, 1, 0];
m4.lookAt(eye, target, up, camera);
m4.inverse(camera, view);
objects.forEach(function(obj, ndx) {
var viewElement = obj.viewElement;
// get viewElement's position
var rect = viewElement.getBoundingClientRect();
if (rect.bottom < 0 || rect.top > gl.canvas.clientHeight ||
rect.right < 0 || rect.left > gl.canvas.clientWidth) {
return; // it's off screen
}
var width = rect.right - rect.left;
var height = rect.bottom - rect.top;
var left = rect.left;
var bottom = gl.canvas.clientHeight - rect.bottom - 1;
gl.viewport(left, bottom, width, height);
gl.scissor(left, bottom, width, height);
if (showRenderingArea) {
gl.clear(gl.COLOR_BUFFER_BIT);
}
var projection = m4.perspective(30 * Math.PI / 180, width / height, 0.5, 100);
m4.multiply(projection, view, viewProjection);
var uni = obj.uniforms;
var world = uni.u_world;
m4.identity(world);
m4.rotateY(world, time * obj.ySpeed, world);
m4.rotateZ(world, time * obj.zSpeed, world);
m4.transpose(m4.inverse(world, uni.u_worldInverseTranspose), uni.u_worldInverseTranspose);
m4.multiply(viewProjection, uni.u_world, uni.u_worldViewProjection);
gl.useProgram(obj.programInfo.program);
// calls gl.bindBuffer, gl.enableVertexAttribArray, gl.vertexAttribPointer
twgl.setBuffersAndAttributes(gl, obj.programInfo, obj.bufferInfo);
// calls gl.bindTexture, gl.activeTexture, gl.uniformXXX
twgl.setUniforms(obj.programInfo, uni);
// calls gl.drawArrays or gl.drawElements
twgl.drawBufferInfo(gl, obj.bufferInfo);
});
}
if (true) { // animated
var renderContinuously = function(time) {
render(time);
requestAnimationFrame(renderContinuously);
}
requestAnimationFrame(renderContinuously);
} else {
var requestId;
var renderRequest = function(time) {
render(time);
requestId = undefined;
}
// If animated
var queueRender = function() {
if (!requestId) {
requestId = requestAnimationFrame(renderRequest);
}
}
window.addEventListener('resize', queueRender);
window.addEventListener('scroll', queueRender);
queueRender();
}
* {
box-sizing: border-box;
-moz-box-sizing: border-box;
}
body {
font-family: monospace;
margin: 0;
}
#c {
position: absolute;
top: 0;
width: 100vw;
height: 100vh;
}
#outer {
width: 100%;
z-index: 2;
position: absolute;
top: 0px;
}
#content {
margin: auto;
padding: 2em;
}
#b {
width: 100%;
text-align: center;
}
.list-item {
border: 1px solid black;
margin: 2em;
padding: 1em;
width: 200px;
display: inline-block;
}
.list-item .view {
width: 100px;
height: 100px;
float: left;
margin: 0 1em 1em 0;
}
.list-item .description {
padding-left: 2em;
}
#media only screen and (max-width : 500px) {
#content {
width: 100%;
}
.list-item {
margin: 0.5em;
}
.list-item .description {
padding-left: 0em;
}
}
<script src="//twgljs.org/dist/4.x/twgl-full.min.js"></script>
<body>
<canvas id="c"></canvas>
<div id="outer">
<div id="content">
<div id="b">item list</div>
<div id="list"></div>
</div>
</div>
</body>
<script id="list-item-template" type="notjs">
<div class="view"></div>
<div class="description">Lorem ipsum dolor sit amet, conse ctetur adipi scing elit. </div>
</script>
<script id="vs" type="notjs">
uniform mat4 u_worldViewProjection;
uniform vec3 u_lightWorldPos;
uniform mat4 u_world;
uniform mat4 u_viewInverse;
uniform mat4 u_worldInverseTranspose;
attribute vec4 a_position;
attribute vec3 a_normal;
attribute vec2 a_texcoord;
varying vec4 v_position;
varying vec2 v_texCoord;
varying vec3 v_normal;
varying vec3 v_surfaceToLight;
varying vec3 v_surfaceToView;
void main() {
v_texCoord = a_texcoord;
v_position = (u_worldViewProjection * a_position);
v_normal = (u_worldInverseTranspose * vec4(a_normal, 0)).xyz;
v_surfaceToLight = u_lightWorldPos - (u_world * a_position).xyz;
v_surfaceToView = (u_viewInverse[3] - (u_world * a_position)).xyz;
gl_Position = v_position;
}
</script>
<script id="fs" type="notjs">
precision mediump float;
varying vec4 v_position;
varying vec2 v_texCoord;
varying vec3 v_normal;
varying vec3 v_surfaceToLight;
varying vec3 v_surfaceToView;
uniform vec4 u_lightColor;
uniform vec4 u_diffuseMult;
uniform sampler2D u_diffuse;
uniform vec4 u_specular;
uniform float u_shininess;
uniform float u_specularFactor;
vec4 lit(float l ,float h, float m) {
return vec4(1.0,
abs(l),//max(l, 0.0),
(l > 0.0) ? pow(max(0.0, h), m) : 0.0,
1.0);
}
void main() {
vec4 diffuseColor = texture2D(u_diffuse, v_texCoord) * u_diffuseMult;
vec3 a_normal = normalize(v_normal);
vec3 surfaceToLight = normalize(v_surfaceToLight);
vec3 surfaceToView = normalize(v_surfaceToView);
vec3 halfVector = normalize(surfaceToLight + surfaceToView);
vec4 litR = lit(dot(a_normal, surfaceToLight),
dot(a_normal, halfVector), u_shininess);
vec4 outColor = vec4((
u_lightColor * (diffuseColor * litR.y +
u_specular * litR.z * u_specularFactor)).rgb,
diffuseColor.a);
gl_FragColor = outColor;
}
</script>
If you have a phone you can see a similar one fullscreen here.

Make "widget" for SVG-group in D3.js

I am using D3 to manipulate an SVG, that contains several "widgets" that have behavior and can be controlled eg via events. For instance I have a spinning fan. It should be possible to turn on and off the fan. I have been able to build that in D3, but not in an elegant way, and with all the code being global. What I want to end up with is something as below:
Creation of "widget", as known from jQuery:
d3.select('svg').append('g').attr('id', 'myFan').fan();
And then I would like to turn on and off with smth like the following, also as known from jQuery:
d3.select('#myFan').fan('start')
d3.select('#myFan').fan('stop')
Is it possible to achieve this in D3, ie to create such a "widget"?
Is there generally a different approach to such a problem, when using D3?
My current unelegant solution with global code:
Robert asked for this. Code at Codepen: link.
Javascript
var fan = d3.select('body')
.append('svg')
.attr('width', 200)
.attr('height', 200)
.append('g')
.attr('class', 'fan')
.attr('id', 'myFan')
.attr('transform', 'translate(75,75)')
// Static, background disc
fan.append('circle')
.attr('cx',0)
.attr('cy',0)
.attr('r',60)
// Dynamic, rotating path
var blade = fan.append('path')
.attr('d', 'M 0 0 L -30 15 L -60 0 Z L 30 -15 L 60 0 Z ')
.attr('transform', 'translate(50,50)')
.attr('transform', 'rotate(90)');
// Static, hub
fan.append('circle')
.attr('cx', 0)
.attr('cy', 0)
.attr('r', 10)
var rotation = 0; // degrees
var speed = 10; // degree per call
function rotate() {
rotation = (rotation + speed) % 360;
blade.attr('transform', 'rotate('+rotation+')')
}
setInterval(rotate, 100);
function stop() { speed = 0; }
function start() { speed = 10; }
var ctrlPanel = d3.select('body').append('div');
ctrlPanel.append('button').text('Start').on('click', start);
ctrlPanel.append('button').text('Stop').on('click', stop);
CSS
path {
fill: red;
strok: blue;
stroke-width: 3px;
}
.fan circle {
fill: lightgray;
stroke: black;
stroke-width: 3px;
}
.fan path {
fill: darkgray;
stroke: black;
stroke-width: 3px;
}

Resources