I'm trying to add an ID to a canvas using JavaScript however I'm trying to modify the following specific code. Please note, I am only assuming that this is where I would set the attribute. Cheers for any help.
THREE.CanvasRenderer = function ( parameters ) {
console.log( 'THREE.CanvasRenderer', THREE.REVISION );
parameters = parameters || {};
var _this = this,
_renderData, _elements, _lights,
_projector = new THREE.Projector(),
_canvas = parameters.canvas !== undefined
? parameters.canvas
: document.createElement( 'canvas' ),
_canvasWidth = _canvas.width,
_canvasHeight = _canvas.height,
_canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
_canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
_viewportX = 0,
_viewportY = 0,
_viewportWidth = _canvasWidth,
_viewportHeight = _canvasHeight,
_pixelRatio = 1,
_context = _canvas.getContext( '2d', {
alpha: parameters.alpha === true
} ),
You can just set the id property directly:
_canvas.id = 'whatever';
Edit
The above code should work, but it will need to be after the large variable initialization block you have:
// start var initialization
var _this = this,
_renderData, _elements, _lights,
_projector = new THREE.Projector(),
_canvas = parameters.canvas !== undefined
? parameters.canvas
: document.createElement( 'canvas' ),
_canvasWidth = _canvas.width,
_canvasHeight = _canvas.height,
_canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
_canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
_viewportX = 0,
_viewportY = 0,
_viewportWidth = _canvasWidth,
_viewportHeight = _canvasHeight,
_pixelRatio = 1,
_context = _canvas.getContext( '2d', {
alpha: parameters.alpha === true
} ),
... more code,
theEnd = true;
// end var initialization
_canvas.id = 'whatever';
^ this whole thing is one big var initialization. At some point there it will end and there will probably be a semicolon. That's where you will add the id code.
I think you were getting an unexpected token error because you were trying to add some code between the commas in the var initialization.
Related
based on this question
How to use LUT with JavaScript?
I tried to use this code
http://jsfiddle.net/gxu080ve/1/
var img = new Image,
canvas = document.getElementById("myCanvas"),
ctx = canvas.getContext("2d"),
src = "http://i.imgur.com/0vcCTK9.jpg?1"; // insert image url here
img.crossOrigin = "Anonymous";
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage( img, 0, 0 );
// alternateImage(img, canvas, ctx);
localStorage.setItem( "savedImageData", canvas.toDataURL("image/png") );
loadNew();
}
img.src = src;
// make sure the load event fires for cached images too
if ( img.complete || img.complete === undefined ) {
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
}
var imgLut = new Image,
canvasLut = document.getElementById("myCanvasLut"),
ctxLut = canvasLut.getContext("2d"),
srcLut = "https://gm1.ggpht.com/nX2ZUYrMwPSXu5zGeeoMKyZP_R4nE205ivAdc3_yaccMEy8QYInfY_ynUB-NmrjvPKn0i1k7bdtHyk3Ul99ndvjvoCASud8FdIdq1fRrqDOCGK01rXgZZQ34ATKvtrkoysUCBmTUG70ZW_-TQxHExbu8gjhH-haIg0EuiWgJSxkL45jE1B4xWaOQNQXgJtmb7i1bSVcRgdmJq0XbttjsZnZn3YTW_LYw_3F-WyEEryTRritkZm6CW6NgaoVUfGH6XIaHp5Igs_dzm01lci9XwvoUwS0KA85w3npkjseL0zZX6u-pYWbSXOzkTLDJDMKPpOPt1VH6UUwARlD1YH1dQb0qdq4FrN8_beghJc00UaO9WHgyLyQ-NXMXFt5zXpeKuWtGwWtB0bzDhEvUXUhoDeOwaTbHlEjv3NgrqfzzpLBfLMM9J2BZLZodaEFA6WiroIsq70Qh6g_yMCVg02oi3s-L_2SSW2duayIIcfljyOxmC5AHbjzS2i-4RnKlVzK5Ge39wmiXX_4wtL0nb5XeDPwGbqqJsCPaeIYFN7z43HW6bA--5E3pUo3mjxLPTMSa8T-omZIw7w=w1896-h835-l75";
function loadNew(){
imgLut.crossOrigin = "Anonymous2";
imgLut.onload = function() {
canvasLut.width = imgLut.width;
canvasLut.height = imgLut.height;
ctxLut.drawImage( imgLut, 0, 0 );
filterImage(img, imgLut, canvasLut, ctxLut);
localStorage.setItem( "savedImageDataLut", canvasLut.toDataURL("image/png") );
}
imgLut.src = srcLutbyte;
// make sure the load event fires for cached images too
if ( imgLut.complete || imgLut.complete === undefined ) {
imgLut.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
imgLut.src = srcLutbyte;
}
}
function alternateImage(img, canvastoapply, ctxToApply){
//var c=document.getElementById("myCanvas");
//var img=document.getElementById("scream");
ctxToApply.drawImage(img,0,0);
var imgData=ctxToApply.getImageData(0,0,canvastoapply.width,canvastoapply.height);
// invert colors
for (var i=0;i<imgData.data.length;i+=4){
imgData.data[i]=255-imgData.data[i];
imgData.data[i+1]=255-imgData.data[i+1];
imgData.data[i+2]=255-imgData.data[i+2];
imgData.data[i+3]=255;
}
ctxToApply.putImageData(imgData,0,0);
};
function filterImage(img, filter, canvastoapply, ctxToApply){
//var c=document.getElementById("myCanvas");
//var img=document.getElementById("scream");
// ctxToApply.drawImage(img,0,0);
var lutWidth = canvasLut.width;
var imgData=ctx.getImageData(0,0,canvas.width,canvas.height);
var filterData=ctxToApply.getImageData(0,0,canvastoapply.width,canvastoapply.height);
// invert colors
for (var i=0;i<imgData.data.length;i+=4){
var r=Math.floor(imgData.data[i]/4);
var g=Math.floor(imgData.data[i+1]/4);
var b=Math.floor(imgData.data[i+2]/4);
var a=255;
var lutX = (b % 8) * 64 + r;
var lutY = Math.floor(b / 8) * 64 + g;
var lutIndex = (lutY * lutWidth + lutX)*4;
var Rr = filterData.data[lutIndex];
var Gg = filterData.data[lutIndex+1];
var Bb = filterData.data[lutIndex+2];
imgData.data[i] = filterData.data[lutIndex];
imgData.data[i+1] = filterData.data[lutIndex+1];
imgData.data[i+2] = filterData.data[lutIndex+2];
imgData.data[i+3] = 255;
}
ctx.putImageData(imgData,0,0);
for the attached LUT and it does not work properly because it only has 5 colums instead of 8. Of course I read the comment from How to use LUT with JavaScript? which says "This code only applies for 64x64x64 3DLUT images. The parameters vary if your LUT has other dimensions; the / 4, * 64, % 8, / 8 must be changed for other dimensions, but in this question's scope the LUT is 64x64x64."
i tried to do so and only ended in a mess.
What would I please have to change to make it work?
I'm trying to modify a script to work for what I need it to do and keep getting the "TypeError: undefined is not an object ... I can't figure out why though. I've copy and pasted pretty much everything. The problem line as setting the font to Adobe Garamond.
Script listener has these lines that I think are related but, I don't know JS enough to get it.
var idfontPostScriptName = stringIDToTypeID( "fontPostScriptName" );
desc22.putString( idfontPostScriptName, """AGaramondPro-Regular""" );
var idFntN = charIDToTypeID( "FntN" );
desc22.putString( idFntN, """Adobe Garamond Pro""" );
var idFntS = charIDToTypeID( "FntS" );
desc22.putString( idFntS, """Regular""" );
My script looks like
// this script is a variation of the script addTimeStamp.js that is installed with PH7
//OPENED document has size
if ( documents.length > 0 )
{
var originalDialogMode = app.displayDialogs;
app.displayDialogs = DialogModes.ERROR;
var originalRulerUnits = preferences.rulerUnits;
preferences.rulerUnits = Units.PIXELS;
try
{
var docRef = activeDocument;
// Now create a text layer at the front
var myLayerRef = docRef.artLayers.add();
myLayerRef.kind = LayerKind.TEXT;
myLayerRef.name = "Filename";
var myTextRef = myLayerRef.textItem;
// strip the extension off
var fileNameNoExtension = docRef.name;
fileNameNoExtension = fileNameNoExtension.split( "." );
if ( fileNameNoExtension.length > 1 ) {
fileNameNoExtension.length--;
}
fileNameNoExtension = fileNameNoExtension.join(".");
myTextRef.contents = fileNameNoExtension;
// off set the text to be in the middle
myTextRef.position = new Array( docRef.width / 2, docRef.height / 2 );
myTextRef.size = 135;
myTextRef.textItem.font = 'AGaramondPro-Regular';
}
catch( e )
{
// An error occurred. Restore ruler units, then propagate the error back
// to the user
preferences.rulerUnits = originalRulerUnits;
app.displayDialogs = originalDialogMode;
throw e;
}
// Everything went Ok. Restore ruler units
preferences.rulerUnits = originalRulerUnits;
app.displayDialogs = originalDialogMode;
}
else
{
alert( "You must have a document open to add the filename!" );
}
Oh my hell. Just answered my own question again. Sorry guys.
myTextRef.font = 'AGaramondPro-Regular';
Today I was happily typing bits of code into my js app, and frequently building using browserify.
Then all of a sudden, browserify started throwing a weird error. It did no longer like my let declarations (which I have quite a lot of).
Suspecting that it somehow no longer accepted ES6 code, I googled on how to specify the Javascript language version, without luck. No one seemed to have the same error with browserify. I also tried deleting my node_modules folder and doing a clean npm install. No dice.
This is the error I get:
events.js:141
throw er; // Unhandled 'error' event
^
SyntaxError: The keyword 'let' is reserved (119:1) while parsing C:\Users\Jon\Auchitect\frontend\js\cons\designs\plate\BoundedPlane.js while parsing file: C:\Users\Jon\Auchitect\frontend\js\cons\designs\plate\BoundedPlane.js
at DestroyableTransform.end [as _flush] (C:\Users\Jon\Auchitect\frontend\node_modules\insert-module-globals\index.js:96:21)
at DestroyableTransform.<anonymous> (C:\Users\Jon\Auchitect\frontend\node_modules\insert-module-globals\node_modules\readable-stream\lib\_stream_transform.js:115:49)
at DestroyableTransform.g (events.js:260:16)
at emitNone (events.js:67:13)
at DestroyableTransform.emit (events.js:166:7)
at prefinish (C:\Users\Jon\Auchitect\frontend\node_modules\insert-module-globals\node_modules\readable-stream\lib\_stream_writable.js:465:12)
at finishMaybe (C:\Users\Jon\Auchitect\frontend\node_modules\insert-module-globals\node_modules\readable-stream\lib\_stream_writable.js:473:7)
at endWritable (C:\Users\Jon\Auchitect\frontend\node_modules\insert-module-globals\node_modules\readable-stream\lib\_stream_writable.js:485:3)
at DestroyableTransform.Writable.end (C:\Users\Jon\Auchitect\frontend\node_modules\insert-module-globals\node_modules\readable-stream\lib\_stream_writable.js:455:41)
at DestroyableTransform.onend (C:\Users\Jon\Auchitect\frontend\node_modules\module-deps\node_modules\through2\node_modules\readable-stream\lib\_stream_readable.js:495:10)
npm ERR! Test failed. See above for more details.
This is my setup:
package.json:
{
"name": "frontend",
"private": true,
"version": "0.1.0",
"main": "./js/main.js",
"directories": {
"doc": "doc"
},
"scripts": {
"test": "node build_test.js",
"start": "node build_main.js"
},
"repository": {
"type": "git",
"url": "git+https://loldrup#bitbucket.org/loldrup/auchitect.git"
},
"author": "Jon Loldrup",
"license": "UNLICENSED",
"homepage": "https://bitbucket.org/loldrup/auchitect#readme",
"dependencies": {
"gl-matrix-common": "*",
"gl-matrix-mat3": "*",
"ndarray": "*",
"ndarray-householder-qr": "*",
"ndarray-matrix-vector-product": "*",
"ndarray-ops": "*",
"three": "*",
"three-orbit-controls": "*"
},
"devDependencies": {
"browserify": "*",
"qunitjs": "*"
},
"browser": {}
}
I use the build_test.js script when developing. It looks like this:
var browserify = require('browserify');
var fs = require('fs');
var options = {
basedir: './js/',
debug: true,
noParse: ['three', 'qunitjs']
};
var outputFileStream = fs.createWriteStream('./js/test_bundle.js');
var b = browserify('./test.js', options);
b.bundle().pipe(outputFileStream); // process.stdout
This is my BoundedPlane.js file:
"use strict";
var THREE = require('three');
var BoundedPlane_prototype = require('./BoundedPlane_prototype');
var utils_mat = require('../../../utils/mat');
var utils_matrix = require('../../../utils/matrix');
require('../../../utils/three/Lin3');
require('../../../utils/three/misc');
// the local (relative) plate index, given an absolute azimuth and polar index entry:
// +--------+--------+--------+
// | plate0 | plate1 | plate2 |
// +--------+--------+--------+
// | plate3 | plate4 | plate5 |
// +--------+--------+--------+
// | plate6 | plate7 | plate8 |
// +--------+--------+--------+
// assumes that the normal vector given as argument is normalized
THREE.BoundedPlane = function ( constant, normal, center, instanceDebug ) {
THREE.Plane.call(this, normal, constant);
this.center = center;
this.normalPoint_vector = this.normal.clone().multiplyScalar(constant); // this point might at any time be out of sync with this.normal and this.constant. Access only through the this.normalPoint() function.
this.bindingBPs = [];
this.boundingPoints = [];
this.instanceDebug = instanceDebug || false;
};
THREE.BoundedPlane.prototype = BoundedPlane_prototype;
THREE.BoundedPlane.prototype.constructor = THREE.BoundedPlane;
Object.freeze( THREE.BoundedPlane );
THREE.BoundedPlane_from_pivot = function ( pivotLength, lowLeft, upLeft, lowRight, instanceDebug, visualDebug ) {
if ( instanceDebug ) {
if ( typeof lowLeft.debug !== "undefined" ) { console.log( "lowLeft.debug: ", lowLeft.debug ); }
if ( typeof upLeft.debug !== "undefined" ) { console.log( "upLeft.debug: ", upLeft.debug ); }
if ( typeof lowRight.debug !== "undefined" ) { console.log( "lowRight.debug: ", lowRight.debug ); }
}
var pivotAxis = new THREE.Lin3( upLeft, lowLeft.clone() ).project_end_to_Vector3( lowRight.sub(upLeft) );
var pivotLever = new THREE.Lin3( lowLeft, upLeft.clone() ).reject_end_to_Lin3( pivotAxis );
var pivotCenter = pivotAxis.end;
var leverSpan = pivotLever.length();
if ( instanceDebug && typeof lowLeft.debug !== "undefined" ) { console.log( "pivotCenter: ", pivotCenter ); }
// put an orthogonal circle with radius 'pivotLength' in lowLeft and find its
// tangent point by a line intersecting the point 'pivotCenter':
var center = new THREE.Vector2( 0, 0 );
var point = new THREE.Vector2( leverSpan, 0 );
var radius = pivotLength;
// get one out of two solutions in a local coordinate system of the plane spanned by the circle:
var tangentPoint_local_2D = utils_mat.circle_tangent_point( center, radius, point )[1];
// state the solution in a local 3D basis:
var tangentPoint_local_3D = new THREE.Vector3( tangentPoint_local_2D.x, 0, tangentPoint_local_2D.y );
// find the (local) basis vectors that were implicitly used when finding the tangentPoint:
var b_x = pivotLever.delta().normalize();
var b_z = pivotAxis.delta().clone().cross( b_x ).normalize();
var b_y = b_z.clone().cross( b_x ).normalize();
// convert the solution to the global 3D space:
var tangentPoint = utils_matrix.changeBasis( tangentPoint_local_3D, b_x, b_y, b_z, true );
var tangentLine = tangentPoint.sub( pivotLever.delta() );
var normal = tangentLine.cross( pivotAxis.delta() ).normalize();
var constant = pivotCenter.clone().projectOnVector( normal ).length();
if ( utils_mat.vectors_negatively_oriented( pivotCenter, normal ) ) { // if true, one has to walk the opposite way of the normal, in order to get to the plane
constant = -1 * constant; }
THREE.BoundedPlane.call( this, constant, normal, pivotCenter, instanceDebug );
if ( false && typeof visualDebug !== 'undefined' && visualDebug.debug ) {
// ONLY FOR TESTING!!
// transform tangentPoint2:
var tangentPoint2 = utils_matrix.changeBasis( tangentPoint2_local_3D, b_x, b_z, b_y, true);
// add lowLeft to tangentPoint to make tangentPoint absolute:
var abs_tangentPoint2 = tangentPoint2.clone().add(lowLeft);
var tangentLine2 = abs_tangentPoint2.clone().sub(pivotCenter); // put in THREE.Line and add a ".cross" method to THREE.Line ?
var pivotAxisVector = upLeft.clone().sub(lowRight);
var new_normal_inverse = pivotAxisVector.cross(tangentLine2.clone()).normalize();
console.log( "tangentPoint2: ", tangentPoint2 );
console.log( "abs_tangentPoint2: ", abs_tangentPoint2 );
console.log( "normal: ", normal );
console.log( "new_normal_inverse: ", new_normal_inverse );
var abs_tangentPoint2_mesh = new THREE.PointHelper(abs_tangentPoint2, 4);
visualDebug.aScene.add(abs_tangentPoint2_mesh); //, fixPoint0_res1_mesh
// also add an axis helper:
var axisHelper_mesh = new THREE.AxisHelper(50);
visualDebug.aScene.add(axisHelper_mesh);
// x = red
// y = green
// z = blue
}
};
THREE.BoundedPlane_from_pivot.prototype = BoundedPlane_prototype;
THREE.BoundedPlane_from_parallel_projection = function ( aBoundedPlane, offset, flip, instanceDebug, visualDebug ) { // all fixPoint1's (presumably..)
let normal = aBoundedPlane.normal.clone();
// ***THIS IS LINE 119 ***
// assumes that the normal vector of 'aBoundedPlane' is already normalized:
let center = aBoundedPlane.center.clone().add(normal.multiplyScalar(offset)); // which "de-normalizes" normal...
// so please restore 'normal' after messing with it:
normal.x = aBoundedPlane.normal.x;
normal.y = aBoundedPlane.normal.y;
normal.z = aBoundedPlane.normal.z;
let constant = aBoundedPlane.constant + offset;
if ( utils_mat.vectors_negatively_oriented( center, normal ) ) // if true, one has to walk the opposite way of the normal, in order to get to the plane
{ constant = -1 * constant; }
if ( flip ) { normal.multiplyScalar(-1); constant = -1 * constant; }
THREE.BoundedPlane.call( this, constant, normal, center, instanceDebug );
};
THREE.BoundedPlane_from_parallel_projection.prototype = BoundedPlane_prototype;
THREE.BoundedPlane_pivoted90_from_twoBPs = function ( mainBP, otherBP, intended_BP_width, instanceDebug, vd ) {
var constant, normal, center, scalar;
//if ( typeof vd !== 'undefined' && vd.debug ) { console.log( "BoundedPlane_pivoted90_from_twoBPs: got visualdebug" ); }
let intersection = utils_mat.plane_plane_intersection( mainBP, otherBP, false, vd );
if ( otherBP.point_on_face_side(mainBP.center) ) {
normal = mainBP.normal.clone().cross( intersection.orientation ).normalize(); }
else { normal = intersection.orientation.clone().cross( mainBP.normal ).normalize(); }
center = intersection.point.clone().projectOnVector( normal ); // fixme: remove clone?
constant = center.length(); // has to happen prior to reflecting the center
// Ensure that center stays within the intended width of the new BP:
center.projectOnPlane( mainBP.normal );
scalar = 1 - ( ( intended_BP_width / 2 ) / mainBP.normalPoint().length() );
center.add( mainBP.normalPoint().multiplyScalar( scalar ) );
var rolledBP = new THREE.BoundedPlane_rolled90_from_twoBPs( mainBP, otherBP, instanceDebug, vd );
center.sub( rolledBP.normalPoint() );
if ( mainBP.point_strictly_on_face_side( center ) ) {
center = mainBP.reflect_vector( center ); }
if ( utils_mat.vectors_negatively_oriented( center, normal ) ) { // if true, one has to walk the opposite way of the normal, in order to get to the plane
constant = -1 * constant; }
THREE.BoundedPlane.call( this, constant, normal, center, instanceDebug );
if ( typeof vd !== 'undefined' && vd.debug ) {
var mainBP_plane = new vd.THREE.PlaneHelper( mainBP.normal, mainBP.center, 10, 2);
var mainBP_center = new vd.THREE.VectorHelper( mainBP.center.clone() ).setColor( 0x00ffff );
var otherBP_plane = new vd.THREE.PlaneHelper( otherBP.normal, otherBP.center, 10, 2, 0xff0000, 0xff0000 );
var otherBP_center = new vd.THREE.VectorHelper( otherBP.center.clone() ).setColor( 0x00ffff );
var newBP_plane = new vd.THREE.PlaneHelper( normal.clone(), center.clone(), vd.size, vd.size/5, vd.color );
var newBP_normal = new vd.THREE.VectorHelper( normal.clone() ).setColor( 0xffff00 );
var newBP_center = new vd.THREE.VectorHelper( center.clone() ).setColor( 0xff7777 );
vd.aScene.add( newBP_plane, mainBP_plane, otherBP_plane, /*newBP_normal, newBP_center, mainBP_center, otherBP_center */ );
// also check out the 'rolled' plane:
var rolledBP_plane = new vd.THREE.PlaneHelper( rolledBP.normal, rolledBP.center, 10, 2, 0x0055aa);
var rolledBP_center = new vd.THREE.VectorHelper( rolledBP.center.clone() ).setColor( 0xff00ff ); // lilla
var rolledBP_normal = new vd.THREE.VectorHelper( rolledBP.normal.clone() ).setColor( 0xff00ff ); // lilla
var rolledBP_normalPoint = new vd.THREE.VectorHelper( rolledBP.normalPoint.clone() ).setColor( 0xff0077 );
console.log( "rolledBP: ", rolledBP );
vd.aScene.add( rolledBP_plane, /*rolledBP_center, rolledBP_normal,*/ rolledBP_normalPoint );
// also add an axis helper:
// var axisHelper_mesh = new THREE.AxisHelper(50);
// vd.aScene.add(axisHelper_mesh);
// x = red
// y = green
// z = blue
}
};
THREE.BoundedPlane_pivoted90_from_twoBPs.prototype = BoundedPlane_prototype;
THREE.BoundedPlane_pivoted90_from_BP_and_2_Vectors = function ( aBP, v0, v1, intended_BP_width, instanceDebug, visualDebug ) {
let delta, constant, normalish, normal, center, length, scalar;
delta = v1.sub(v0);
normalish = delta.cross(aBP.normal); // this vector might be pointing the wrong way, depending on the order og args v0 and v1. It also lacks normalization.
normalish = v0.projectOnVector( normalish ); // this vector removes the ordering uncertainty, but still lacks the normalization.
constant = normalish.length();
normal = v1.copy(normalish).normalize();
center = normalish;
// Ensure that center stays within the intended width of the new BP:
center.projectOnPlane( aBP.normal );
scalar = 1 - ( ( intended_BP_width / 2 ) / aBP.normalPoint().length() );
center.add( aBP.normalPoint().multiplyScalar( scalar ) );
// The new plane should bend "backwards" in relation to aBP. Thus planes will, per default, tend to form
// a closed form. If other behaviour is desired (concave corners?), add a flag that activates this behaviour
if ( aBP.point_strictly_on_face_side( center ) ) {
center = aBP.reflect_vector( center ); }
THREE.BoundedPlane.call( this, constant, normal, center, instanceDebug );
// we want the normal to point away from the center of 'aBP':
if ( this.point_on_face_side( aBP.center ) ) {
this.normal = this.normal.multiplyScalar( -1 );
this.constant = -1 * this.constant }
};
THREE.BoundedPlane_pivoted90_from_BP_and_2_Vectors.prototype = BoundedPlane_prototype;
THREE.BoundedPlane_rolled90_from_twoBPs = function ( mainBP, otherBP, instanceDebug, vd ) {
let constant, normal, center;
center = mainBP.center.clone().add( otherBP.center ).divideScalar( 2 );
constant = center.length();
let delta = otherBP.center.clone().sub( mainBP.center );
let normals_crossed = mainBP.normal.clone().cross( otherBP.normal ); // this vector might be pointing the wrong way, depending on the order of the vectors being crossed
normal = normals_crossed.clone().normalize(); // fixme: remove clone
if ( utils_mat.vectors_negatively_oriented( center, normal ) ) {
normal.multiplyScalar( -1 ) }
THREE.BoundedPlane.call( this, constant, normal, center, instanceDebug );
if ( typeof vd !== 'undefined' && vd.debug ) {
console.log( "hi" );
let normals_crossed_vh = new vd.THREE.VectorHelper( normals_crossed ).setColor( 0xaa00aa ); // lilla
vd.aScene.add( normals_crossed_vh );
}
};
THREE.BoundedPlane_rolled90_from_twoBPs.prototype = BoundedPlane_prototype;
I replaced all let keywords in the file with good ol' vars. This meant that Browserify no longer complained about the let keywords.
Instead, it complained about line 185, which is empty. However, line 184 contained an error of sorts: a trailing comma in an arguments list. Fixing this error made Browserify compile my code again.
So the problem is one of useability: I got an irrelevant error message for the trailing comma.
EDIT: this was the offending line:
vd.aScene.add( newBP_plane, mainBP_plane, otherBP_plane, /*newBP_normal, newBP_center, mainBP_center, otherBP_center */ );
I assume that this is a bug but if any of you know any work around please let me know.
First of all, the fonts are loaded 101%.
I load Google fonts synchronously
I check with interval to make sure that the font is loaded.
I convert a string into an image (with the below function) by using canvas with success (when
I use English characters)
After rendering a couple English characters I try to render a Greek
word but canvas fall backs to browsers default font.
Firefox doesn't have any issue at all, it works great. The issue is
with Chrome.
Bellow is the function that creates a ribbon-label background image on the top left corner from a given string (PS: this function return imageData that are being merged with other imageData later on):
ImageProcessor.prototype.createLabelImageData = function ( str, size, font, color, backgroundColor, shadowColor, shadowOffsetX, shadowOffsetY, shadowBlur, width, height ) {
this.canvas.width = width || this.settings.width;
this.canvas.height = height || this.settings.height;
this.ctx.clearRect( 0, 0, this.canvas.width, this.canvas.height );
this.ctx.font = "Bold " + ( size || 64 ) + "px " + ( font || "Arial" );
this.ctx.textAlign = "center";
this.ctx.textBaseline = "middle";
var labelHeight = ( size || 64 ) + ( ( size || 64 ) / 4 );
var labelTop = this.canvas.height / 2 - labelHeight / 2;
var labelWidth = this.canvas.width;
var strLen = this.ctx.measureText( str + " " ).width;
var side = Math.sqrt( ( strLen * strLen ) / 2 );
var distance = Math.sqrt( ( side * side ) - ( ( strLen / 2 ) * ( strLen / 2 ) ) );
this.ctx.save();
this.ctx.rotate( -Math.PI / 4 );
this.ctx.translate( -this.canvas.width / 2, -this.canvas.height / 2 + distance );
this.ctx.fillStyle = ( backgroundColor || '#f00' );
this.ctx.beginPath();
this.ctx.moveTo( 0, labelTop );
this.ctx.lineTo( labelWidth, labelTop );
this.ctx.lineTo( labelWidth, labelTop + labelHeight );
this.ctx.lineTo( 0, labelTop + labelHeight );
this.ctx.closePath();
this.ctx.fill();
if ( shadowColor ) {
this.ctx.shadowColor = shadowColor;
this.ctx.shadowOffsetX = ( shadowOffsetX || 0 );
this.ctx.shadowOffsetY = ( shadowOffsetY || 0 );
this.ctx.shadowBlur = ( shadowBlur || size || 64 );
}
this.ctx.fillStyle = ( color || "#fff" );
this.ctx.fillText( str, this.canvas.width / 2, this.canvas.height / 2 );
this.ctx.restore();
var imageData = this.ctx.getImageData( 0, 0, this.canvas.width, this.canvas.height );
this.canvas.width = this.settings.width;
this.canvas.height = this.settings.height;
return imageData;
};
Well after some testing, trial and error and many many hours of reading...
I found out that it doesn't matter if the font has been downloaded when you want to use it in canvas. What worked for me before anything else and any check was to create n*2 div elements (n the number of fonts loaded) and position them outside of the view-port. n*2 because in some I added font-weight:bold.
Bottom line is that the exact font you wish to use in canvas must be:
Preloaded
Create a dummy dom element with innerHTML text of all language
variations (latin & greek in my case).
Keep in mid that you have to create extra elements for the bold variation of the font.
Here is the code that I'm currently using to preload fonts and make sure they are available in canvas.
Vise.prototype.initializeFonts = function ( settings, globalCallback ) {
var that = this; // reference to parent class
/********************************************
********************************************
**
**
** Default settings
**
**
********************************************
********************************************/
var defaults = {
interval: 100,
timeout: 10000,
families: [
'Open+Sans+Condensed:300,300italic,700:latin,greek',
'Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800:latin,greek',
'Roboto+Condensed:300italic,400italic,700italic,400,700,300:latin,greek',
'Roboto:400,100,100italic,300,300italic,400italic,500,500italic,700,700italic,900,900italic:latin,greek'
]
};
// initialization
this.fonts = new Fonts( $.extend( true, defaults, settings ) );
this.fonts.onload = globalCallback;
this.fonts.load();
};
/********************************************
********************************************
**
**
** Fonts class
**
**
********************************************
********************************************/
function Fonts( settings ) {
this.settings = settings;
this.success = [];
this.fail = [];
this.interval = null;
this.elapsedTime = this.settings.interval;
this.fontDetective = new Detector();
}
Fonts.prototype.load = function () {
WebFont.load( {
google: {
families: this.settings.families
}
} );
for ( var i in this.settings.families ) {
var el, elBold;
var familyStr = this.settings.families[ i ];
var family = familyStr.split( ':' )[ 0 ].replace( /[+]/gi, ' ' );
el = document.createElement( "div" );
el.innerHTML = "Font loader Φόρτωμα γραμματοσειράς";
el.style.fontFamily = family;
el.style.color = "#f00";
el.style.position = "fixed";
el.style.zIndex = 9999;
el.style.left = "9999px";
document.body.appendChild( el );
elBold = document.createElement( "div" );
elBold.innerHTML = "Font loader Φόρτωμα γραμματοσειράς";
elBold.style.fontFamily = family;
elBold.style.fontWeight = "bold";
elBold.style.color = "#f00";
elBold.style.position = "fixed";
elBold.style.zIndex = 9999;
elBold.style.left = "9999px";
document.body.appendChild( elBold );
}
this.interval = setInterval( this.areLoaded.bind( this ), this.settings.interval );
};
Fonts.prototype.areLoaded = function () {
for ( var i in this.settings.families ) {
var familyStr = this.settings.families[ i ];
var family = familyStr.split( ':' )[ 0 ].replace( /[+]/gi, ' ' );
var successIdx, failIdx;
if ( this.fontDetective.detect( family ) ) {
successIdx = this.success.indexOf( family );
failIdx = this.fail.indexOf( family );
if ( successIdx === -1 ) {
this.success.push( family );
console.log( "[" + family + "] was successfully loaded." );
}
if ( failIdx > -1 ) {
this.fail.splice( failIdx, 1 );
}
} else {
successIdx = this.success.indexOf( family );
failIdx = this.fail.indexOf( family );
if ( successIdx > -1 ) {
this.success.splice( successIdx, 1 );
}
if ( failIdx === -1 ) {
this.fail.push( family );
}
}
}
if ( this.elapsedTime >= this.settings.timeout ) {
clearInterval( this.interval );
var err = new Error( "Unable to load fonts: " + this.fail.toString() );
this.onload( err, null );
return;
}
if ( this.success.length === this.settings.families.length ) {
clearInterval( this.interval );
this.onload( null, null );
return;
}
this.elapsedTime += this.settings.interval;
};
This is what worked for me in case someone else has the same issue on chrome.
PS: Take a look at fontdetect.js which I use in my code.
Edit: I am also open to other suggestions on what I could do.
How can I update my window with the onChange event? My solution works, but I need the groups to collapse when not visible.
w.DD.onChange = function() {
switch (this.selection.text){
case 'Headline':
if(w.visiblegroup)
w.visiblegroup.visible = false;
w.visiblegroup = w.texted;
w.texted.visible = true;
break;
}
}
I have tried to use w.show, w.update(with documentation, still not sure what .update actually does) after adding the elements in the case itself. But I can't figure this out.
w.DD.onChange = function() {
switch (this.selection.text){
case 'Headline':
w.add('checkbox', undefined, 'User-Color');
//w.show();
w.update();
break;
}
}
Does anyone have a clue how this might work?
I generally avoid using LayoutManager and do all teh maths by myself which I trust better but that's my humble opinion…
var w = new Window("dialog");
w.preferredSize = [200,200];
w.DD = w.add( 'dropdownlist', undefined, ["A","B"] );
w.DD.selection = 0;
w.DD.alignment = ["fill","top"];
//Setting a stacked group to items overlay
w.gp = w.add('group');
w.gp.orientation = 'stack';
w.gp.alignment = ["fill","top"];
w.gp.alignChildren = ["fill","top"];
w.gp.p1 = w.gp.add('panel',undefined, "A");
w.gp.p2 = w.gp.add('panel',undefined, "B");
//dummy text to show "collapsing"
w.st = w.add('statictext',undefined, "Collapse ?");
w.DD.onChange = function() {
w.gp.p1.visible = w.DD.selection==0;
w.gp.p2.visible = !w.gp.p1.visible;
w.gp.p2.size.height =100;
w.gp.size.height = w.gp.p1.visible? 50 : 100;
w.st.location.y = w.gp.location.y+w.gp.size.height+10;
}
w.onShow = function() {
w.gp.p2.visible=false;
w.gp.size.height = w.gp.p1.size.height = 50;
w.st.location.y = w.gp.location.y+w.gp.size.height+10;
}
w.show();
Loic
To collapse the groups and window you will need to use the layout() method of your window. This will load the LayoutManager that controls the automatic layout behavior for a window or container. The LayoutManager has a method called layout() too, this method invokes the automatic layout behaviour and invoked automatically the first time the window is displayed. Thereafter, the script must invoke it explicitly like so:
window.layout().layout();
An example of how to use the layout manager by Gerald Singelmann:
function main() {
var win = new Window("dialog");
var maingroup = win.add("panel");
maingroup.orientation = "column";
add_group( maingroup );
var show_btn = win.add("button", undefined, "show");
show_btn.onClick = function() {
var txt = "";
for (var n = 0; n < maingroup.children.length; n++) {
txt += maingroup.children[n].edit.text + "\n";
}
alert("Da steht: \n" + txt );
}
win.show();
function add_group( maingroup ) {
var group = maingroup.add( "group" );
group.edit = group.add("edittext", [undefined, undefined, 200, 20], maingroup.children.length );
group.plus = group.add("button", undefined, "+");
group.plus.onClick = add_btn;
group.minus = group.add("button", undefined, "-");
group.minus.onClick = minus_btn;
group.index = maingroup.children.length - 1;
win.layout.layout( true );
return group;
}
function add_btn ( e ) {
add_group( maingroup );
}
function minus_btn ( e ) {
var ix = this.parent.index;
maingroup.remove( maingroup.children[ix] );
win.layout.layout( true );
}
}
source