Browserify: SyntaxError: The keyword 'let' is reserved - javascript

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 */ );

Related

Extruded SVG image in AR.js throws getUniforms of undefined error

I want to import a SVG file into my AR.js scene to be displayed on a marker.
For that I am using the official Three.js SVGLloader[1].
While using this with pure Three.js I am able to load a SVG into my scene and display it.
But when I use the exact same function combined with AR.js I get this error:
TypeError: Cannot read property 'getUniforms' of undefined
setProgram
https://localhost:3000/libs/three/example/vendor/three.js/build/three.js:24307:26
WebGLRenderer.renderBufferDirect
https://localhost:3000/libs/three/example/vendor/three.js/build/three.js:23313:18
renderObject
https://localhost:3000/libs/three/example/vendor/three.js/build/three.js:24041:11
renderObjects
https://localhost:3000/libs/three/example/vendor/three.js/build/three.js:24011:6
WebGLRenderer.render
https://localhost:3000/libs/three/example/vendor/three.js/build/three.js:23798:33
[1] https://threejs.org/docs/#examples/en/loaders/SVGLoader
My code is almost the same like in the example:
/ instantiate a loader
const loader = new SVGLoader();
// load a SVG resource
loader.load(
// resource URL
'data/svgSample.svg',
// called when the resource is loaded
function ( data ) {
const paths = data.paths;
const group = new THREE.Group();
for ( let i = 0; i < paths.length; i ++ ) {
const path = paths[ i ];
const material = new THREE.MeshBasicMaterial( {
color: path.color,
side: THREE.DoubleSide,
depthWrite: false
} );
const shapes = SVGLoader.createShapes( path );
for ( let j = 0; j < shapes.length; j ++ ) {
const shape = shapes[ j ];
const geometry = new THREE.ShapeGeometry( shape );
const mesh = new THREE.Mesh( geometry, material );
group.add( mesh );
}
}
myMarker.add( group ); // add it to the predefined Marker, which works perfectly with other 3d Models but not with this SVG model.
},
// called when loading is in progresses
function ( xhr ) {
console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
},
// called when loading has errors
function ( error ) {
console.log( 'An error happened' );
}
);

pts.js 'NS_ERROR_NOT_AVAILABLE: ' Error when trying to use an image for a particle

I'm wanting to load the same an image for particles in pts.js.
When I try to use a local image from my assets folder I get the error "NS_ERROR_NOT_AVAILABLE:" in the console.
I read somewhere this may be due to the image trying to be used before it has even been loaded in...
I've also tried using an external link to some other image rather than a local one and that works. So not sure what is happening with my local files.
EDIT:
I just tried this on chrome rather than firefox and I'm getting a new and more detailed error message.
"Uncaught DOMException: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The HTMLImageElement provided is in the 'broken' state." in pts.min.js:6.
Still not sure exactly what is wrong.
Pts.quickStart('#hello', 'transparent')
var world
// Loading in image to be used
var myImg = new Image()
myImg.src = '/assets/img/myImage.png'
space.add({
start: (bound, space) => {
// Create world and 100 random points
world = new World(space.innerBound, 1, 0)
let pts = Create.distributeRandom(space.innerBound, 20)
// Create particles and hit them with a random impulse
for (let i = 0, len = pts.length; i < len; i++) {
let p = new Particle(pts[i]).size(i === 0 ? 10 : 20)
p.hit(0, 0)
world.add(p)
}
world.particle(0).lock = true
},
animate: (time, ftime) => {
world.drawParticles((p, i) => {
// Image variable for the particle to be drawn as
form.image(myImg)
})
world.update(ftime)
},
action: (type, px, py) => {
if (type == 'move') {
world.particle(0).position = new Pt(px, py)
}
},
resize: (bound, evt) => {
if (world) world.bound = space.innerBound
}
})
space.bindMouse().bindTouch()
space.play()
For drawing images on canvas, the image needs to be loaded first. You can keep track of it using myImg.addEventListener( 'load', ... ).
Once it's loaded, you can use it in form.image( myImg, ... ) in Pts' animate loop.
Here's a working example based on your code above:
Pts.quickStart( "#pt", "#123" );
//// Demo code starts (anonymous function wrapper is optional) ---
(function() {
var world;
var imgReady = false;
// Loading in image to be used
var myImg = new Image()
myImg.src = 'http://icons.iconarchive.com/icons/icojoy/maneki-neko/256/cat-6-icon.png';
myImg.addEventListener('load', function() {
imgReady = true;
}, false);
space.add( {
start: (bound, space) => {
// Create world and 100 random points
world = new World( space.innerBound, 1, 0 );
let pts = Create.distributeRandom( space.innerBound, 100 );
// Create particles and hit them with a random impulse
for (let i=0, len=pts.length; i<len; i++) {
let p = new Particle( pts[i] ).size( (i===0) ? 30 : 3+Math.random()*space.size.x/50 );
p.hit( Num.randomRange(-50,50), Num.randomRange(-25, 25) );
world.add( p );
}
world.particle( 0 ).lock = true; // lock it to move it by pointer later on
},
animate: (time, ftime) => {
world.drawParticles( (p, i) => {
if (imgReady) {
console.log( p )
form.image(myImg, [p.$subtract( p.radius ), p.$add( p.radius )] );
}
});
world.update( ftime );
},
action:( type, px, py) => {
if (type == "move") {
world.particle( 0 ).position = new Pt(px, py);
}
},
resize: (bound, evt) => {
if (world) world.bound = space.innerBound;
}
});
space.bindMouse().bindTouch();
space.play();
})();

Add an ID to a canvas using JavaScript

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.

Photoshop JS specify font

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';

Canvas Greek google fonts not rendering correctly

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.

Categories

Resources