Meteor, fabricjs canvas on multiple templates causes memory leak - meteor

I have a simple meteor app with two templates using flowrouter to navigate between them. Each template has a single HTML canvas element in it both have a fabricjs canvas assigned and a box drawn.
When I navigate between the two templates while doing a memory performance profile I see the memory continuously increase at every navigation between templates.
I expected the garbage collector to clean up the canvas vars but its not. So something keeping them in context. I can't see what I'm missing here.
Template HTML
<template name="one">
Template One
two
<div>
<canvas id="canvasONE" width="2000" height="1601"></canvas>
</div>
</template>
<template name="two">
Template Two
one
<div>
<canvas id="canvasTWO" width="2000" height="1601"></canvas>
</div>
</template>
// JavaScript
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import './main.html';
//////////////////////////////////////////////
// Template One
Template.one.onRendered( function(){
var canvas = new fabric.Canvas('canvasONE',{selection:true});
var rec = new fabric.Rect({
left: 0,
top: 0,
width: 120,
height: 50,
rx: 4,
ry: 4,
fill: '#64b5f6',
stroke: '#6Ebfff',
strokeWidth: 2,
originX: 'left',
originY: 'top',
lockScalingX: true,
lockScalingY: true
});
canvas.add(rec)
})
/////////////////////////////////////////////////////
// Template Two
Template.two.onRendered( function(){
var canvas = new fabric.Canvas('canvasTWO',{selection:true});
var rec = new fabric.Rect({
left: 0,
top: 0,
width: 120,
height: 50,
rx: 4,
ry: 4,
fill: '#223344',
stroke: '#6Ebfff',
strokeWidth: 2,
originX: 'left',
originY: 'top',
lockScalingX: true,
lockScalingY: true
});
canvas.add(rec)
})
Thanks...
UPDATE: after a few hours debugging, it appears to be DOM related. The meteor template removes the DOM elements but fabric could still be referencing it. The GC leaves it in memory. I added an extra function to each template to try clear the fabric canvas.
Template.one.onDestroyed( function(){
rec = null;
canvas.clear();
canvas.dispose();
$(canvas.wrapperEl).remove()
})
but still seeing the memory leak continue.

The problem was resolved.
I moved the var canvas definition outside of the function blocks to the root of the file, In meteor this makes it global to the scope of the file, not a true application global. The fabricjs canvas clear() dispose() were from a recommendation by one of the authors of fabric posted as an answer to someone else's question,

Related

Nextjs x Framer Motion inertial scrolling with page transition

I've been working on an inertial scrolling implementation within Nextjs using Framer Motion but running into a bit of trouble when animation page transitions using animate presence. I'm hooking into the page scroll progress via useScroll and animating the Y transform with spring physics. The issue, however, is when resetting the window scroll position when navigating between pages. After the component has unmounted, I call window.scrollTo(0,0) via the AnimatePresence onExitComplete callback, but because I'm transforming the page position via spring physics, the scroll reset doesn't complete immediately. So when new pages are mounted, the page transform to reset the scroll is still running.
Additionally, I've included scroll={false} in my Next Link components to prevent the default scroll to top functionality so I can handle this manually via the AnimatePresence component as mentioned above. But this doesn't seem to be working.
There's a bit of code involved so I created a minimal reproduction repo here.
I also notice that passing scrollY to the y property of the variant object prevents the unwanted scrolling behavior on page transition. But passing something like scrollY - 128 breaks the behavior:
const variants = {
hidden: { opacity: 0, x: 0, y: 64 },
enter: { opacity: 1, x: 0, y: 0 },
exit: { opacity: 0, x: 0, y: scrollY },
};
y value in exit variant wasn't being updated to match latest scrollY value. Solution:
useEffect(() => {
return scrollY.onChange((latest) => {
variants.exit.y = -scrollY.current - 128;
});
});

Why doesn't my custom component update when I change properties with setAttribute?

I think I don't quite understand how components and entities work.
I'm using the box component that appears in the a-frame help (https://aframe.io/docs/1.3.0/introduction/writing-a-component.html#example-box-component), and I want to modify a property. When doing so, I thought that the update would be activated but it does nothing. In fact the oldData is always empty and never enters in the update option (except for the first time):
<script>
AFRAME.registerComponent("box", {
...
}
</script>
<a-scene> </a-scene>
<script>
const gScene = document.querySelector("a-scene");
var camara = document.querySelector("[camera]");
camara.setAttribute("position", { x: 0, y: 0, z: 10 });
var p00 = document.createElement("a-entity");
p00.setAttribute("box", { width: 1, height: 1, depth: 1, color: "#f00" });
gScene.appendChild(p00);
p00.setAttribute("height", 3);
p00.setAttribute("color", "#00f");
</script>
First part of the code plot a red box with 1x1x1 dimension. But when I change the height or color attribute, don't do anything. What I have to do to fire the update?
Thanks in advance
You need to update the box attribute - setAttribute("height", XXX) will trigger an update in the height component.
If color is in the box schema, then:
// this updates the color property of the box attribute,
// triggering "update" in the "box" component
p00.setAttribute("box", "color", "red")
// this update the height attribute,
// triggering "update" in the "height" component
p00.setAttribute("height", "10");

How To Prevent CSS Applied to One Three.JS Scene From Being Applied To All Scenes

This may be more of a "you're going to have to do it the long way" type of deal, but here it goes...
When I apply CSS to control the opacity of only one HTML element that is the container of a Three.JS scene in where there are multiple elements that each are a container for their own scene, the CSS applied (even at an inline level) to only one of those elements containing a scene is being applied to all elements that contain a scene and not specifically the one targeted. This happens with any post applied CSS attribute, not just opacity.
The reason why I am attempting this approach at controlling opacity this way is that per my research there is no direct way to set an opacity on a Three.JS group object that contains 1 to N number of meshes. I am (in theory) trying not to have to define all materials with transparency set to "true" and then having to do recursive updates to all meshes in a Three.JS Group object where an animation would fade in/out.
Some of the group objects I'm working with will have many meshes defined in them. Thus, rather than update the opacity of each individual mesh itself contained within a Three.JS group object, my goal was/is to have individual scenes for each type of animation that is capable of having any amount of transparency applied to it run as is then just adjust the HTML element containing that animation's opacity property.
I've tried using one camera and multiple cameras to no avail. I've also tried nesting the containers in one additional element and setting CSS on the parent element but the same issue occurs. I have not tried using multiple renderers as from what I gather in research is that doing so is frowned upon and can lead to performance issues and context limits. The render loop also has "autoClear" set to false so that all scenes render together.
Here is the HTML syntax. You will notice that the first element has a inline style for opacity set to 0.5 and the second element has no inline styling applied:
<div class="three-js-container" id="scene-container-1" style="opacity:0.5;"></div>
<div class="three-js-container" id="scene-container-2"></div>
Here is the Javascript code:
/* Only one renderer instance is created */
var universalRenderer = new THREE.WebGLRenderer({antialias: true, alpha:true});
/* references to all containers are made */
var containerForScene1 = document.getElementById("scene-container-1");
var containerForScene2 = document.getElementById("scene-container-2");
/* two different cameras are created */
var cameraForScene1 = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.001, 1000);
var cameraForScene2 = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.001, 1000);
/* two different scenes are created, one for each element container */
var scene1 = new THREE.Scene();
scene1.userData.element = containerForScene1;
var scene2 = new THREE.Scene();
scene2.userData.element = containerForScene2;
/* the renderer is applied to both scene containers */
containerForScene1.appendChild(universalRenderer.domElement);
containerForScene2.appendChild(universalRenderer.domElement);
When both animations are played, both scenes are rendered at 1/2 opacity rather than just the first scene itself.
Is there a reason why CSS styling applied to one HTML scene containing element is applied to all of the other scene containing elements? Will I just have to suck it up and go the long way around in controlling mesh opacity?
Thanks.
Setting transparency for a THREE.Group:
A Group is just a container. As such, it has children, which are potentially other Groups. But you can only apply transparency to a Material, which is assigned at the Mesh level, not Groups. However, not all is lost, because you can monkey patch Group to allow you to perform the operation seamlessly.
// MONKEY PATCH
Object.defineProperty(THREE.Group.prototype, "transparent", {
set: function(newXP) {
this.traverse(node => {
if (node.material) {
node.material.transparent = newXP
node.material.opacity = (newXP) ? 0.5 : 1
}
})
}
})
// Set up the renderer
const renderer = new THREE.WebGLRenderer({
alpha: true,
antialias: true
})
document.body.appendChild(renderer.domElement)
renderer.setSize(window.innerWidth, window.innerHeight)
const scene = new THREE.Scene()
const size = new THREE.Vector2()
renderer.getSize(size)
const camera = new THREE.PerspectiveCamera(28, size.x / size.y, 1, 1000)
camera.position.set(0, 20, 100)
camera.lookAt(scene.position)
scene.add(camera)
camera.add(new THREE.PointLight(0xffffff, 1))
function render() {
renderer.render(scene, camera)
}
const axis = new THREE.Vector3(0, 1, 0)
function animate() {
requestAnimationFrame(animate)
camera.position.applyAxisAngle(axis, 0.005)
camera.lookAt(scene.position)
render()
}
animate()
// Populate the scene
const cubeGeo = new THREE.BoxBufferGeometry(5, 5, 5)
let opaqueCubes = []
let transparentCubes = []
const randomInRange = () => Math.random() * ((Math.random() <= 0.5) ? -10 : 10)
const opaqueGroup = new THREE.Group()
scene.add(opaqueGroup)
for (let i = 0; i < 10; ++i) {
opaqueGroup.add(new THREE.Mesh(cubeGeo, new THREE.MeshPhongMaterial({
color: "red"
})))
opaqueGroup.children[i].position.set(randomInRange(), randomInRange(), randomInRange())
}
const transparentGroup = new THREE.Group()
scene.add(transparentGroup)
for (let i = 0; i < 10; ++i) {
transparentGroup.add(new THREE.Mesh(cubeGeo, new THREE.MeshPhongMaterial({
color: "green"
})))
transparentGroup.children[i].position.set(randomInRange(-10, 10), randomInRange(-10, 10), randomInRange(-10, 10))
}
// Control the transparency from the input
const xparent = document.getElementById("xparent")
xparent.addEventListener("change", (e) => {
transparentGroup.transparent = xparent.checked
})
html,
body {
padding: 0;
margin: 0;
overflow: hidden;
}
#control {
position: absolute;
top: 0;
left: 0;
padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/105/three.js"></script>
<div id="control">
<label>Make the green ones transparent:<input id="xparent" type="checkbox" /></label>
<div>

How to set dynamic content for InfoBubble using AngularJS?

I use AngularJS. I want to present an InfoBubble with dynamic content and some functions of AngularJS like ng-click, ng-mouseover. Using InfoWindows I had to compile html first and then set the compiled html as the content of the InfoWindows. Unfortunately, this is not working for InfoBubbles. When I add static html it has no problem, but when I add the compiled html it seems to have nothing as content.
var htmlElement = '<div ng-include="\'/home/include/infoBubble.html\'"></div>'
var compiled = $compile(htmlElement)($scope)
infoWindow = new InfoBubble({
content: compiled[0],
shadowStyle: 1,
padding: 0,
backgroundColor: 'rgb(57,57,57)',
borderRadius: 4,
arrowSize: 10,
borderWidth: 1,
borderColor: '#2c2c2c',
disableAutoPan: true,
hideCloseButton: true,
arrowPosition: 30,
backgroundClassName: 'phoney',
arrowStyle: 2
});
infoWindow.open(vm.map, marker);
The problem was that I had no max and min heights and widths. Setting those solved the problem.

Creating an infinite-scroll of meteor collection in angular-meteor

I'm trying to enable infinite scroll for an angular-meteor app I'm working on that draws objects from a meteor/mongo collection.
I've adapted step 12 of the angular-meteor tutorial to use pagination for the app I'm working on, and now I'd like to convert to infinite scrolling. I've been trying to adapt both the code from the tutorial and this example from ngInfiniteScroll for my purposes.
I imagine I'll need to use reactive variables, autorun, etc. similar to the tutorial, but I don't really know how to adapt it for infinite scroll. Considering the example below, how should I adjust my controller for it to use infinite scrolling, drawing from a database, with good angular-meteor practices for production?
Demo ngInfiniteScroll HTML:
<div infinite-scroll='loadMore()' infinite-scroll-distance='2'>
<img ng-repeat='image in images' ng-src='http://placehold.it/225x250&text={{image}}'>
</div>
Demo ngInfiniteScroll Function inside controller:
$scope.images = [1, 2, 3, 4, 5, 6, 7, 8];
$scope.loadMore = function() {
var last = $scope.images[$scope.images.length - 1];
for(var i = 1; i <= 8; i++) {
$scope.images.push(last + i);
}
};
My angular-meteor pagination code inside controller:
$scope.page = 1;
$scope.perPage = 1;
$scope.sort = {'_id': -1};
$scope.orderProperty = '1';
$scope.images = $meteor.collection(function() {
return Images.find({}, {
sort : $scope.getReactively('sort')
});
});
$meteor.autorun($scope, function() {
$meteor.subscribe('images', {
limit: parseInt($scope.getReactively('perPage')),
skip: (parseInt($scope.getReactively('page')) - 1) * parseInt($scope.getReactively('perPage')),
sort: $scope.getReactively('sort')
}).then(function(){
$scope.imagesCount = $meteor.object(Counts ,'numberOfImages', false);
});
});
$scope.pageChanged = function(newPage) {
$scope.page = newPage;
};
Please look at this basic example https://github.com/barbatus/ng-infinite-scroll.
Controller there re-subscribes every time onLoadMore is executed.
There is also a deployed demo http://ng-infinite-scroll.meteor.com.
Make sure this time angular.module('infinite-scroll').value('THROTTLE_MILLISECONDS', 500) is set properly (not very small) to avoid very frequent requests.

Resources