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.
Related
This code allows me to click on a thumbnail and see the original in a new window.
Clicking outside of the window does an autoclose.
So far so good.
However if the image is larger than the screen resolution I have to doubleclick on the Title Bar and then right click and "view image" to make it full screen. How can I change the code to prevent the image going off the screen?
<script language="JavaScript" type="text/javascript">
PositionX = 10;
PositionY = 10;
defaultWidth = 600;
defaultHeight = 400;
var AutoClose = true;
function popImage(imageURL,imageTitle){
var imgWin = window.open('','_blank','scrollbars=no,resizable=1,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY);
if( !imgWin ) { return true; } //popup blockers should not cause errors
imgWin.document.write('<html><head><title>'+imageTitle+'<\/title><script type="text\/javascript">\n'+
'function resizeWinTo() {\n'+
'if( !document.images.length ) { document.images[0] = document.layers[0].images[0]; }'+
'var oH = document.images[0].height, oW = document.images[0].width;\n'+
'if( !oH || window.doneAlready ) { return; }\n'+ //in case images are disabled
'window.doneAlready = true;\n'+ //for Safari and Opera
'var x = window; x.resizeTo( oW + 200, oH + 200 );\n'+
'var myW = 0, myH = 0, d = x.document.documentElement, b = x.document.body;\n'+
'if( x.innerWidth ) { myW = x.innerWidth; myH = x.innerHeight; }\n'+
'else if( d && d.clientWidth ) { myW = d.clientWidth; myH = d.clientHeight; }\n'+
'else if( b && b.clientWidth ) { myW = b.clientWidth; myH = b.clientHeight; }\n'+
'if( window.opera && !document.childNodes ) { myW += 16; }\n'+
'x.resizeTo( oW = oW + ( ( oW + 200 ) - myW ), oH = oH + ( (oH + 200 ) - myH ) );\n'+
'var scW = screen.availWidth ? screen.availWidth : screen.width;\n'+
'var scH = screen.availHeight ? screen.availHeight : screen.height;\n'+
'if( !window.opera ) { x.moveTo(Math.round((scW-oW)/2),Math.round((scH-oH)/2)); }\n'+
'}\n'+
'<\/script>'+
'<\/head><body onload="resizeWinTo();"'+(AutoClose?' onblur="self.close();"':'')+'>'+
(document.layers?('<layer left="0" top="0">'):('<div style="position:absolute;left:0px;top:0px;display:table;">'))+
'<img src='+imageURL+' alt="Loading image ..." title="" onload="resizeWinTo();">'+
(document.layers?'<\/layer>':'<\/div>')+'<\/body><\/html>');
imgWin.document.close();
if( imgWin.focus ) { imgWin.focus(); }
return false;
}
</script>
<a href="./mypic.jpg" onclick="return popImage(this.href,'Magnify');">
<img src="./mythumb.jpg" width="500" height="333" border="0"></a>
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.
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 found this great piece of code on jsfiddle for fading between two colors onScroll using jQuery and the Color plugin.
What I would like to do is be able to fade three or more colors onScroll down the page.
I have tried (failing miserably) to edit the code myself but am just too new to JS and jQuery.
Help please?
$(document).ready(function(){
//** notice we are including jquery and the color plugin at
//** http://code.jquery.com/color/jquery.color-2.1.0.js
var scroll_pos = 0;
var animation_begin_pos = 0; //where you want the animation to begin
var animation_end_pos = 1000; //where you want the animation to stop
var beginning_color = new $.Color( 'rgb(210,50,98)' ); //we can set this here, but it'd probably be better to get it from the CSS; for the example we're setting it here.
var ending_color = new $.Color( 'rgb(0,197,209)' ); ;//what color we want to use in the end
$(document).scroll(function() {
scroll_pos = $(this).scrollTop();
if(scroll_pos >= animation_begin_pos && scroll_pos <= animation_end_pos ) {
// console.log( 'scrolling and animating' );
//we want to calculate the relevant transitional rgb value
var percentScrolled = scroll_pos / ( animation_end_pos - animation_begin_pos );
var newRed = beginning_color.red() + ( ( ending_color.red() - beginning_color.red() ) * percentScrolled );
var newGreen = beginning_color.green() + ( ( ending_color.green() - beginning_color.green() ) * percentScrolled );
var newBlue = beginning_color.blue() + ( ( ending_color.blue() - beginning_color.blue() ) * percentScrolled );
var newColor = new $.Color( newRed, newGreen, newBlue );
//console.log( newColor.red(), newColor.green(), newColor.blue() );
$('body').animate({ backgroundColor: newColor }, 0);
} else if ( scroll_pos > animation_end_pos ) {
$('body').animate({ backgroundColor: ending_color }, 0);
} else if ( scroll_pos < animation_begin_pos ) {
$('body').animate({ backgroundColor: beginning_color }, 0);
} else { }
});
});
Here is the fiddle:
http://jsfiddle.net/cgspicer/V4qh9/
Similar to Sterling's answer, my first attempt was to kind of insert another checkpoint for the third color. This process, as in Sterling's solution, begins to precipitate the necessity of sub-functions.
See it here: http://jsfiddle.net/5uU6y/1/
A better and more complete solution, in which you can declare multiple colors, can be achieved by creating an array which stores your beginning, ending, and color values that you can check against when the window is scrolled.
Here's that solution ( see it in action here: http://codepen.io/cgspicer/pen/tomvq/ )
$(document).ready(function(){
/**
requires http://code.jquery.com/color/jquery.color-2.1.0.js
*/
var colorsNPoints = [
{ 'begin' : 0, 'end': 100, 'color': 'rgb(220,20,60)' },
{ 'begin' : 100, 'end': 110, 'color': 'rgb(0,0,0)' },
{ 'begin' : 110, 'end': 210, 'color': 'rgb(50,205,50)' },
{ 'begin' : 210, 'end': 310, 'color': 'rgb(255,215,0)' },
{ 'begin' : 310, 'end': 410, 'color': 'rgb(220,20,60)' },
{ 'begin' : 410, 'end': 420, 'color': 'rgb(0,0,0)' },
{ 'begin' : 420, 'end': 520, 'color': 'rgb(50,205,50)' },
{ 'begin' : 520, 'end': 620, 'color': 'rgb(255,215,0)' },
{ 'begin' : 620, 'end': 720, 'color': 'rgb(220,20,60)' },
{ 'begin' : 720, 'end': 730, 'color': 'rgb(0,0,0)' },
{ 'begin' : 730, 'end': 830, 'color': 'rgb(50,205,50)' },
{ 'begin' : 830, 'end': 930, 'color': 'rgb(255,215,0)' }
];
$(document).scroll(function() {
var scrollPosition = $(this).scrollTop();
var currentRange = checkRange( scrollPosition, colorsNPoints );
if ( currentRange !== undefined ) {
console.log( currentRange );
var newColor = recalcColor( currentRange.prevColor, currentRange.nextColor, currentRange.progress );
$('body').css({ backgroundColor: newColor }, 0);
} else {
// do nothing, we're not within any ranges
}
});
// sub-functions
/**
* checks which, if any, of the scroll ranges the window is currently on
* returns an object containing necessary values
*/
function checkRange( yValue, rangesObj ) {
// loop over the object containing our ranges
for ( var i=0; i < rangesObj.length; i++ ) {
var rangeToCheck = rangesObj[i];
// check to see if we are within said range
if ( yValue >= rangeToCheck.begin && yValue <= rangeToCheck.end ) {
// set up a new object for refinement and return
var currentRangeObj = {};
currentRangeObj.prevColor = rangesObj[i-1] ? rangesObj[i-1].color : rangeToCheck.color; // store old color, falls back to range's color if no previous color exists
currentRangeObj.nextColor = rangeToCheck.color; // store new color
currentRangeObj.progress = calcPercentScrolled( rangeToCheck.begin, rangeToCheck.end, yValue ); //calculate the progress within the current range
return currentRangeObj;
} else {
}
}
}
/**
* calculates current percent scrolled
**/
function calcPercentScrolled( begin, end, current ) {
return (current - begin) / ( end - begin );
}
/**
* calculates new color
**/
function recalcColor( begin, end, factor ) {
var begin = $.Color( begin ),
end = $.Color( end );
var newRed = begin.red() + ( ( end.red() - begin.red() ) * factor );
var newGreen = begin.green() + ( ( end.green() - begin.green() ) * factor );
var newBlue = begin.blue() + ( ( end.blue() - begin.blue() ) * factor );
return $.Color( newRed, newGreen, newBlue );
}
});
Hope this helps!
Try this. It's the same idea as the original code with a couple of minor additions. You can try to do it for n colors using the same idea using an array of start positions, end positions, and starting colors if you want some practice with Javascript. (And a better implementation)
Fiddle
$(document).ready(function(){
//** notice we are including jquery and the color plugin at
//** http://code.jquery.com/color/jquery.color-2.1.0.js
var body_end = $(document).height() / ;
var animation_begin_pos = 0; //where you want the animation to begin
var animation_middle_pos = body_end / 3;
var animation_end_pos = body_end / (3/2); //where you want the animation to stop
var beginning_color = new $.Color( 'rgb(210,50,98)' ); //we can set this here, but it'd probably be better to get it from the CSS; for the example we're setting it here.
var middle_color = new $.Color('rgb(255,0,0)');
var ending_color = new $.Color( 'rgb(0,197,209)' ); ;//what color we want to use in the end
/* */
function getPercentScrolled(scroll_pos, beginning_pos, end_pos){
return (scroll_pos - beginning_pos) / (end_pos - beginning_pos);
}
function getNewRGB(start_color, end_color, percentScrolled){
var newRed = start_color.red() + ( ( end_color.red() - start_color.red() ) * percentScrolled );
var newGreen = start_color.green() + ( ( end_color.green() - start_color.green() ) * percentScrolled );
var newBlue = start_color.blue() + ( ( end_color.blue() - start_color.blue() ) * percentScrolled );
console.log(newRed, newGreen, newBlue);
console.log(percentScrolled);
newRed = ((newRed > 0.0) ? newRed : 0.0);
newGreen = ((newGreen > 0.0) ? newGreen : 0.0);
newBlue = ((newBlue > 0.0) ? newBlue : 0.0);
return {red: newRed, green: newGreen, blue: newBlue};
}
$(document).scroll(function() {
var scroll_pos = $(this).scrollTop();
if(scroll_pos >= animation_begin_pos && scroll_pos <= animation_middle_pos ) {
//we want to calculate the relevant transitional rgb value
var percentScrolled = getPercentScrolled(scroll_pos, animation_begin_pos, animation_end_pos);
var updatedColor = getNewRGB(beginning_color, middle_color, percentScrolled);
var newColor = new $.Color( updatedColor['red'], updatedColor['green'], updatedColor['blue'] );
$('body').animate({ backgroundColor: newColor }, 0);
}
else if ( scroll_pos >= animation_middle_pos && scroll_pos < animation_end_pos) {
percentScrolled = getPercentScrolled(scroll_pos, animation_middle_pos, animation_end_pos);
updatedColor = getNewRGB(middle_color, ending_color, percentScrolled);
newColor = new $.Color( updatedColor['red'], updatedColor['green'], updatedColor['blue'] );
$('body').animate({ backgroundColor: newColor }, 0);
}
else if ( scroll_pos > animation_middle_pos ) {
$('body').animate({ backgroundColor: ending_color }, 0);
}
else if ( scroll_pos < animation_begin_pos ) {
$('body').animate({ backgroundColor: beginning_color }, 0);
}
});
});
When I click browse server in ckeditor the image browser popup doesnt appear.I am facing problem only in Google Chrome.I am using 18.0.1025.152 m verion of Google Chrome
I have made changes in ckeditor/plugins/popup/plugin.js
try
{
// Chrome 18 is problematic, but it's not really needed here (#8855).
var ua = navigator.userAgent.toLowerCase();
if ( ua.indexOf('chrome/18' ) == -1 )
{
popupWindow.moveTo( left, top );
popupWindow.resizeTo( width, height );
}
popupWindow.focus();
popupWindow.location.href = url;
}
catch ( e )
{
popupWindow = window.open( url, null, options, true );
}
I followed this link enter link description here
But I am unable to resolve the issue.Can anyone help
If you edit the source files you have to repackage them again. It's much simpler to update to CKEditor 3.6.3 and get all the other bug fixes.
I am using opencart 1.5.1.3 ckeditor. I edit the /admin/view/javascript/ckeditor/ckeditor.js and re-align the javascript code with http://jsbeautifier.org/
I have tried with the patch from ckeditor community and little modifications. It works!
http://dev.ckeditor.com/ticket/8855
So if anyone has face the similar issue like me in opencart you can try with below changes.
+++ b/v1.5.1.3/admin/view/javascript/ckeditor/ckeditor.js
## -9190,8 +9190,21 ## For licensing, see LICENSE.html or http://ckeditor.com/license
var s = window.open('', null, p, true);
if (!s) return false;
try {
- s.moveTo(r, q);
- s.resizeTo(n, o);
+ // s.moveTo(r, q);
+ // s.resizeTo(n, o);
+ // Chrome 18 is problematic, but it's not really needed here (#8855).
+ var ua = navigator.userAgent.toLowerCase();
+ var useResize = true;
+ if (ua.indexOf('chrome') > -1) {
+ var chromeVersion = ua.replace(/^.*chrome\/([\d]+).*$/i, '$1')
+ if(chromeVersion >= 18) {
+ useResize = false;
+ }
+ }
+ if (useResize) {
+ s.moveTo( r, q );
+ s.resizeTo( n, o );
+ }
s.focus();
s.location.href = m;
} catch (t) {
I'm using the CKEditor 3.6.2 that comes bundled with primefaces-extensions, so upgrading is not that easy. But executing the following fix against the page also worked. I pasted it in the config file, to be sure that it is fired after the CKEDITOR variable is initialized.
CKEDITOR.editor.prototype['popup'] = function( url, width, height, options ) {
width = width || '80%';
height = height || '70%';
if ( typeof width == 'string' && width.length > 1 && width.substr( width.length - 1, 1 ) == '%' )
width = parseInt( window.screen.width * parseInt( width, 10 ) / 100, 10 );
if ( typeof height == 'string' && height.length > 1 && height.substr( height.length - 1, 1 ) == '%' )
height = parseInt( window.screen.height * parseInt( height, 10 ) / 100, 10 );
if ( width < 640 )
width = 640;
if ( height < 420 )
height = 420;
var top = parseInt( ( window.screen.height - height ) / 2, 10 ),
left = parseInt( ( window.screen.width - width ) / 2, 10 );
options = ( options || 'location=no,menubar=no,toolbar=no,dependent=yes,minimizable=no,modal=yes,alwaysRaised=yes,resizable=yes,scrollbars=yes' ) +
',width=' + width +
',height=' + height +
',top=' + top +
',left=' + left;
var popupWindow = window.open( '', null, options, true );
// Blocked by a popup blocker.
if ( !popupWindow )
return false;
try
{
// Chrome 18 is problematic, but it's not really needed here (#8855).
var ua = navigator.userAgent.toLowerCase();
if ( ua.indexOf( ' chrome/18' ) == -1 )
{
popupWindow.moveTo( left, top );
popupWindow.resizeTo( width, height );
}
popupWindow.focus();
popupWindow.location.href = url;
}
catch ( e )
{
popupWindow = window.open( url, null, options, true );
}
return true;
}
$(document).ready(
function() {
setContentHeight();
makeInstructionsTogglable();
window.onbeforeunload = function() {
if (editor.isDirty()) {
return "Are you sure you want to navigate away? You have unsaved changes."
}
};
}
);
$(window).resize(function() {
setContentHeight();
});