How to fix 'Assertion occurred after test had finished' with Qunit - javascript

I have a function for an animation that uses a callback. The function uses promises:
export function createExpandCollapseCallback(
containerSelector,
toExpandCollapseSelector,
animationDuration
) {
return function () {
if ( animating ) {
return;
}
animating = true;
if ( console.time ) {
console.time( 'animation' );
}
const container = document.querySelector( containerSelector );
const toExpandCollapse = container.querySelector(
toExpandCollapseSelector
);
toExpandCollapse.style.display = 'block';
let animation;
if ( expanded ) {
const moveUp = ( moved ) => -moved;
animation = animateHeight(
toExpandCollapse,
animationDuration,
moveUp
);
} else {
const moveDown = ( moved, height ) => moved - height;
animation = animateHeight(
toExpandCollapse,
animationDuration,
moveDown
);
}
animation.then( () => {
animating = false;
if ( console.timeEnd ) {
console.timeEnd( 'animation' );
}
updateExpanded( ! expanded );
} );
};
}
function animateHeight( children, animationDuration, changeTop ) {
const height = children.clientHeight;
const frameDuration = ( 1 / 60 ) * 1000; // 60 fps
return new Promise( ( resolve ) => {
const slideSomeMore = function ( moved, computationTime = 0 ) {
const start = window.performance.now();
const next = start + frameDuration;
while ( moved < height ) {
if ( window.performance.now() < next ) {
continue;
}
const incrementPerMs = height / animationDuration;
const uncomputedIncrement = incrementPerMs * computationTime;
moved = moved + ( incrementPerMs + uncomputedIncrement ) * 1.2;
children.style.top = `${ changeTop( moved, height ) }px`;
const end = window.performance.now();
setTimeout( () => slideSomeMore( moved, end - start ), 0 );
return;
}
resolve();
};
slideSomeMore( 0 );
} );
}
I have set up Qunit in an HTML file. First I render UI in a playground div inside the HTML file and then call the animation callback. My goal is to simulate the animation and verify that the simulation duration is between the animation-duration(3rd parameter passed to the function) + the error margin. I first render a UI AND then perform the animation. Here is the Html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Rusty Inc. Org Chart WordPress Plugin JavaScript Tests</title>
<link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.7.1.css">
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<div >
<h1>Here is the playground</h1>
<div id="playground"></div>
</div>
<script src="https://code.jquery.com/qunit/qunit-2.7.1.js"></script>
<script type="module">
import { subscribe, updateTree, updateSecretURL, getTree , createExpandCollapseCallback } from '../framework.js';
import { ui } from '../ui.js';
const q = QUnit;
q.module( 'Framework' );
q.test('animation duraion is as much provided', assert=>{
const tree = {"id":1,"name":"Rusty Corp.","emoji":"🐕","parent_id":null,"children":[{"id":2,"name":"Food","emoji":"🥩","parent_id":1,"children":[{"id":"cltp","name":"new","emoji”:”🤢”,”parent_id":2,"children":[]}]},{"id":3,"name":"Canine Therapy","emoji":"😌","parent_id":1,"children":[{"id":4,"name":"Massages","emoji":"💆","parent_id":3,"children":[]},{"id":5,"name":"Games","emoji":"🎾","parent_id":3,"children":[]},{"id":"8xza","name":"lol","emoji":"😀","parent_id":3,"children":[]},{"id":"lctu","name":"new","emoji":"🔥","parent_id":3,"children":[]}]}]};
updateTree( tree );
const secretURL= "random.com"
const insertionElement = document.getElementById("playground")
ui(tree,secretURL,true,insertionElement)
const pluginUI = document.querySelector(`#ui > button`)
console.log('lel', pluginUI );
const durationTime = 1500;
const errorMargin = 200;
const dur2 = 3000
const expandCollapse = createExpandCollapseCallback( '#ui > .team','.children', durationTime );
const done = assert.async();
const start = window.performance.now();
expandCollapse()
const end = window.performance.now();
assert.ok( end - start < durationTime + errorMargin, 'someshit untrue' );
done();
} )
</script>
</body>
</html>
When I run the test I get an alternating message between the testing passing and failing due to assertion being called after the test has finished. This happens every time I refresh, If the test passes and I hit refresh it fails and passes if I refresh again. In this manner, It alternates between passing and failing every time I refresh.
Here are the screenshots for both states:
passing test screenshot
Failing test screensht

Related

How to render the actual value of the scroll percentage?

I have this piece of code
import React from 'react'
const App = () => {
function getScrollPercent() {
var h = document.documentElement,
b = document.body,
st = 'scrollTop',
sh = 'scrollHeight';
var scrollPercent = Math.round((h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100);
//get the percentage of scroll
return (isNaN(scrollPercent) ? '' : scrollPercent)
}
return (
<p>{`${getScrollPercent()}%`}</p>
)
the problem is when I scroll the scrollPercent doesn't refresh in real time but only when the scroll stop, so scrollPercent can pass from 0% to 100% and not display all the numbers between 0 and 100, so the question is how can I modify my piece of code to display the actual value of scrollPercent even when I scroll
You will need to use a useEffect to add an event listener that will listen for the scroll event. Then, you can register a function that will re-calculate the scroll position when the user scrolls up or down the page.
import React, { useEffect, useState } from "react";
function getScrollPercent() {
var h = document.documentElement,
b = document.body,
st = "scrollTop",
sh = "scrollHeight";
var scrollPercent = Math.round(
((h[st] || b[st]) / ((h[sh] || b[sh]) - h.clientHeight)) * 100
);
//get the percentage of scroll
return isNaN(scrollPercent) ? "" : scrollPercent;
}
const App = () => {
// this represents the current calculated scroll percentage
// maybe initialize this to something other than empty string
const [scrollPercentage, setScrollPercentage] = useState("");
useEffect(() => {
function handleScroll() {
const newScrollPercentage = getScrollPercent();
// calculate and set the new scroll percentage
setScrollPercentage(newScrollPercentage);
}
window.addEventListener("scroll", handleScroll, true);
// clean up event listener when component unmounts
return () => {
window.removeEventListener('scroll', handleScroll, true);
}
}, []);
// this contains extra styling to demo, so that you can see the
// scroll value change when scrolling, probably remove these style props
return (
<div style={{ height: "3000px" }}>
<p style={{ position: "fixed" }}>{`${scrollPercentage}%`}</p>
</div>
);
};
export default App;
Codesandbox Link to example: Codesandbox
You need to use window.addEventListener to reach what you want.
import React from "react";
const App = () => {
const [scroll, setScroll] = React.useState("");
function getScrollPercent() {
var h = document.documentElement,
b = document.body,
st = "scrollTop",
sh = "scrollHeight";
var scrollPercent = Math.round(
((h[st] || b[st]) / ((h[sh] || b[sh]) - h.clientHeight)) * 100
);
setScroll(isNaN(scrollPercent) ? "" : scrollPercent);
}
React.useEffect(() => {
window.addEventListener("scroll", getScrollPercent);
return () => {
window.removeEventListener("scroll", getScrollPercent);
};
}, []);
return (
<div style={{ height: "1000px" }}>
<p style={{ position: "fixed" }}>{`${scroll}%`}</p>
</div>
);
};
export default App;
Codesanbox Link: https://codesandbox.io/s/unruffled-field-3l3z8?file=/src/App.js:0-664

"useRefs" variable an initial value of a div reference?

Im trying to build an audio progess bar with react hooks. I was following a tutorial with react class based components but got a little lost with refs.
How can I give my useRef variables an initial value of the div ref when the page loads?
As soon as I start playing then the I get an error saying cant read offsetwidth of null. Obviously timeline ref is null as it doesnt have an initial value. How can I connect it to the div with id of timeline in the useEffect hook?
const AudioPlayer = () => {
const url = "audio file";
const [audio] = useState(new Audio(url));
const [duration, setDuration] = useState(0);
const [currentTime, setCurrentTime] = useState(0)
let timelineRef = useRef()
let handleRef = useRef()
useEffect(() => {
audio.addEventListener('timeupdate', e => {
setDuration(e.target.duration);
setCurrentTime(e.target.currentTime)
let ratio = audio.currentTime / audio.duration;
let position = timelineRef.offsetWidth * ratio;
positionHandle(position);
})
}, [audio, setCurrentTime, setDuration]);
const mouseMove = (e) => {
positionHandle(e.pageX);
audio.currentTime = (e.pageX / timelineRef.offsetWidth) * audio.duration;
};
const mouseDown = (e) => {
window.addEventListener('mousemove', mouseMove);
window.addEventListener('mouseup', mouseUp);
};
const mouseUp = (e) => {
window.removeEventListener('mousemove', mouseMove);
window.removeEventListener('mouseup', mouseUp);
};
const positionHandle = (position) => {
let timelineWidth = timelineRef.offsetWidth - handleRef.offsetWidth;
let handleLeft = position - timelineRef.offsetLeft;
if (handleLeft >= 0 && handleLeft <= timelineWidth) {
handleRef.style.marginLeft = handleLeft + "px";
}
if (handleLeft < 0) {
handleRef.style.marginLeft = "0px";
}
if (handleLeft > timelineWidth) {
handleRef.style.marginLeft = timelineWidth + "px";
}
};
return (
<div>
<div id="timeline" ref={(timeline) => { timelineRef = timeline }}>
<div id="handle" onMouseDown={mouseDown} ref={(handle) => { handleRef = handle }} />
</div>
</div>
)
}
The useRef() hook returns a reference to an object, with the current property. The current property is the actual value useRef points to.
To use the reference, just set it on the element:
<div id="timeline" ref={timelineRef}>
<div id="handle" onMouseDown={mouseDown} ref={handleRef} />
And then to use it, you need to refer to the current property:
let position = current.timelineRef.offsetWidth * ratio;
And positionHandle - you shouldn't actually set styles on elements in React in this way. Use the setState() hook, and set the style using JSX.
const positionHandle = (position) => {
let timelineWidth = timelineRef.current.offsetWidth - handleRef.current.offsetWidth;
let handleLeft = position - timelineRef.current.offsetLeft;
if (handleLeft >= 0 && handleLeft <= timelineWidth) {
handleRef.current.style.marginLeft = handleLeft + "px";
}
if (handleLeft < 0) {
handleRef.current.style.marginLeft = "0px";
}
if (handleLeft > timelineWidth) {
handleRef.current.style.marginLeft = timelineWidth + "px";
}
};
In addition, the ref can be also used for other values, such as the new Audio(url), and be extracted from the current property:
const { current: audio } = useRef(new Audio(url));

How to correctly wait on state to update/render instead of using a delay/timeout function?

I will attempt to keep this brief, but I am not 100% sure of the correct method of achieving what I am aiming for. I have been thrown in the deep end with React with not much training, so I have most likely been going about most of this component incorrectly, a point in the right direction will definitely help, I don't really expect for someone to completely redo my component for me as it's quite long.
I have a navigation bar SubNav, that finds the currently active item based upon the url/path, this will then move an underline element that inherits the width of the active element. To do this, I find the position of the active item and position accordingly. The same goes for when a user hovers over another navigation item, or when the window resizes it adjusts the position accordingly.
I also have it when at lower resolutions, when the nav gets cut off to have arrows appear to scroll left/right on the navigation to view all navigation items.
Also, if on a lower resolution and the currently active navigation item is off screen, the navigation will scroll to that item and then position the underline correctly.
This, currently works as I have it in my component, this issue is, I don't believe I have done this correctly, I am using a lodash function delay to delay at certain points (I guess to get the correct position of certain navigation items, as it isn't correct at the time of the functions call), which I feel is not the way to go. This is all based on how fast the page loads etc and will not be the same for each user.
_.delay(
() => {
setSizes(getSizes()),
updateRightArrow(findItemInView(elsRef.length - 1)),
updateLeftArrow(findItemInView(0));
},
400,
setArrowStyle(styling)
);
Without using the delay, the values coming back from my state are incorrect as they haven't been set yet.
My question is, how do I go about this correctly? I know my code below is a bit of a read but I have provided a CODESANBOX to play about with.
I have 3 main functions, that all sort of rely on one another:
getPostion()
This function finds the active navigation item, checks if it's within the viewport, if it is not, then it changes the left position of the navigation so it's the leftmost navigation item on the screen, and via setSizes(getSizes()) moves the underline directly underneath.
getSizes()
This is called as an argument within setSizes to update the sizes state, which returns the left and right boundaries of all navigation items
getUnderlineStyle()
This is called as an argument within setUnderLineStyle within the getSizes() function to update the position of the underline object in relation to the position of active navigation item grabbed from the sizes state, but I have to pass the sizesObj as an argument in setSizes as the state has not been set. I think this is where my confusion began, I think I was under the impression, that when I set the state, I could then access it. So, I started using delay to combat.
Below is my whole Component, but can be seen working in CODESANBOX
import React, { useEffect, useState, useRef } from "react";
import _ from "lodash";
import { Link, Route } from "react-router-dom";
import "../../scss/partials/_subnav.scss";
const SubNav = props => {
const subNavLinks = [
{
section: "Link One",
path: "link1"
},
{
section: "Link Two",
path: "link2"
},
{
section: "Link Three",
path: "link3"
},
{
section: "Link Four",
path: "link4"
},
{
section: "Link Five",
path: "link5"
},
{
section: "Link Six",
path: "link6"
},
{
section: "Link Seven",
path: "link7"
},
{
section: "Link Eight",
path: "link8"
}
];
const currentPath =
props.location.pathname === "/"
? "link1"
: props.location.pathname.replace(/\//g, "");
const [useArrows, setUseArrows] = useState(false);
const [rightArrow, updateRightArrow] = useState(false);
const [leftArrow, updateLeftArrow] = useState(false);
const [sizes, setSizes] = useState({});
const [underLineStyle, setUnderLineStyle] = useState({});
const [arrowStyle, setArrowStyle] = useState({});
const [activePath, setActivePath] = useState(currentPath);
const subNavRef = useRef("");
const subNavListRef = useRef("");
const arrowRightRef = useRef("");
const arrowLeftRef = useRef("");
let elsRef = Array.from({ length: subNavLinks.length }, () => useRef(null));
useEffect(
() => {
const reposition = getPosition();
subNavArrows(window.innerWidth);
if (!reposition) {
setSizes(getSizes());
}
window.addEventListener(
"resize",
_.debounce(() => subNavArrows(window.innerWidth))
);
window.addEventListener("resize", () => setSizes(getSizes()));
},
[props]
);
const getPosition = () => {
const activeItem = findActiveItem();
const itemHidden = findItemInView(activeItem);
if (itemHidden) {
const activeItemBounds = elsRef[
activeItem
].current.getBoundingClientRect();
const currentPos = subNavListRef.current.getBoundingClientRect().left;
const arrowWidth =
arrowLeftRef.current !== "" && arrowLeftRef.current !== null
? arrowLeftRef.current.getBoundingClientRect().width
: arrowRightRef.current !== "" && arrowRightRef.current !== null
? arrowRightRef.current.getBoundingClientRect().width
: 30;
const activeItemPos =
activeItemBounds.left * -1 + arrowWidth + currentPos;
const styling = {
left: `${activeItemPos}px`
};
_.delay(
() => {
setSizes(getSizes()),
updateRightArrow(findItemInView(elsRef.length - 1)),
updateLeftArrow(findItemInView(0));
},
400,
setArrowStyle(styling)
);
return true;
}
return false;
};
const findActiveItem = () => {
let activeItem;
subNavLinks.map((i, index) => {
const pathname = i.path;
if (pathname === currentPath) {
activeItem = index;
return true;
}
return false;
});
return activeItem;
};
const getSizes = () => {
const rootBounds = subNavRef.current.getBoundingClientRect();
const sizesObj = {};
Object.keys(elsRef).forEach(key => {
const item = subNavLinks[key].path;
const el = elsRef[key];
const bounds = el.current.getBoundingClientRect();
const left = bounds.left - rootBounds.left;
const right = rootBounds.right - bounds.right;
sizesObj[item] = { left, right };
});
setUnderLineStyle(getUnderlineStyle(sizesObj));
return sizesObj;
};
const getUnderlineStyle = (sizesObj, active) => {
sizesObj = sizesObj.length === 0 ? sizes : sizesObj;
active = active ? active : currentPath;
if (active == null || Object.keys(sizesObj).length === 0) {
return { left: "0", right: "100%" };
}
const size = sizesObj[active];
const styling = {
left: `${size.left}px`,
right: `${size.right}px`,
transition: `left 300ms, right 300ms`
};
return styling;
};
const subNavArrows = windowWidth => {
let totalSize = sizeOfList();
_.delay(
() => {
updateRightArrow(findItemInView(elsRef.length - 1)),
updateLeftArrow(findItemInView(0));
},
300,
setUseArrows(totalSize > windowWidth)
);
};
const sizeOfList = () => {
let totalSize = 0;
Object.keys(elsRef).forEach(key => {
const el = elsRef[key];
const bounds = el.current.getBoundingClientRect();
const width = bounds.width;
totalSize = totalSize + width;
});
return totalSize;
};
const onHover = active => {
setUnderLineStyle(getUnderlineStyle(sizes, active));
setActivePath(active);
};
const onHoverEnd = () => {
setUnderLineStyle(getUnderlineStyle(sizes, currentPath));
setActivePath(currentPath);
};
const scrollRight = () => {
const currentPos = subNavListRef.current.getBoundingClientRect().left;
const arrowWidth = arrowRightRef.current.getBoundingClientRect().width;
const subNavOffsetWidth = subNavRef.current.clientWidth;
let nextElPos;
for (let i = 0; i < elsRef.length; i++) {
const bounds = elsRef[i].current.getBoundingClientRect();
if (bounds.right > subNavOffsetWidth) {
nextElPos = bounds.left * -1 + arrowWidth + currentPos;
break;
}
}
const styling = {
left: `${nextElPos}px`
};
_.delay(
() => {
setSizes(getSizes()),
updateRightArrow(findItemInView(elsRef.length - 1)),
updateLeftArrow(findItemInView(0));
},
500,
setArrowStyle(styling)
);
};
const scrollLeft = () => {
const windowWidth = window.innerWidth;
// const lastItemInView = findLastItemInView();
const firstItemInView = findFirstItemInView();
let totalWidth = 0;
const hiddenEls = elsRef
.slice(0)
.reverse()
.filter((el, index) => {
const actualPos = elsRef.length - 1 - index;
if (actualPos >= firstItemInView) return false;
const elWidth = el.current.getBoundingClientRect().width;
const combinedWidth = elWidth + totalWidth;
if (combinedWidth > windowWidth) return false;
totalWidth = combinedWidth;
return true;
});
const targetEl = hiddenEls[hiddenEls.length - 1];
const currentPos = subNavListRef.current.getBoundingClientRect().left;
const arrowWidth = arrowLeftRef.current.getBoundingClientRect().width;
const isFirstEl =
targetEl.current.getBoundingClientRect().left * -1 + currentPos === 0;
const targetElPos = isFirstEl
? targetEl.current.getBoundingClientRect().left * -1 + currentPos
: targetEl.current.getBoundingClientRect().left * -1 +
arrowWidth +
currentPos;
const styling = {
left: `${targetElPos}px`
};
_.delay(
() => {
setSizes(getSizes()),
updateRightArrow(findItemInView(elsRef.length - 1)),
updateLeftArrow(findItemInView(0));
},
500,
setArrowStyle(styling)
);
};
const findItemInView = pos => {
const rect = elsRef[pos].current.getBoundingClientRect();
return !(
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= window.innerHeight &&
rect.right <= window.innerWidth
);
};
const findLastItemInView = () => {
let lastItem;
for (let i = 0; i < elsRef.length; i++) {
const isInView = !findItemInView(i);
if (isInView) {
lastItem = i;
}
}
return lastItem;
};
const findFirstItemInView = () => {
let firstItemInView;
for (let i = 0; i < elsRef.length; i++) {
const isInView = !findItemInView(i);
if (isInView) {
firstItemInView = i;
break;
}
}
return firstItemInView;
};
return (
<div
className={"SubNav" + (useArrows ? " SubNav--scroll" : "")}
ref={subNavRef}
>
<div className="SubNav-content">
<div className="SubNav-menu">
<nav className="SubNav-nav" role="navigation">
<ul ref={subNavListRef} style={arrowStyle}>
{subNavLinks.map((el, i) => (
<Route
key={i}
path="/:section?"
render={() => (
<li
ref={elsRef[i]}
onMouseEnter={() => onHover(el.path)}
onMouseLeave={() => onHoverEnd()}
>
<Link
className={
activePath === el.path
? "SubNav-item SubNav-itemActive"
: "SubNav-item"
}
to={"/" + el.path}
>
{el.section}
</Link>
</li>
)}
/>
))}
</ul>
</nav>
</div>
<div
key={"SubNav-underline"}
className="SubNav-underline"
style={underLineStyle}
/>
</div>
{leftArrow ? (
<div
className="SubNav-arrowLeft"
ref={arrowLeftRef}
onClick={scrollLeft}
/>
) : null}
{rightArrow ? (
<div
className="SubNav-arrowRight"
ref={arrowRightRef}
onClick={scrollRight}
/>
) : null}
</div>
);
};
export default SubNav;
You can make use of useLayoutEffect hook to determine whether the values have been updated and take an action. Since you want to determine whether all the values has been updated, you need to compare old and new values in useEffect. You can refer to the below post to know how to write a usePrevious custom hook
How to compare oldValues and newValues on React Hooks useEffect?
const oldData = usePrevious({ rightArrow, leftArrow, sizes});
useLayoutEffect(() => {
const {rightArrow: oldRightArrow, leftArrow: oldLeftArrow, sizes: oldSizes } = oldData;
if(oldRightArrow !== rightArrow && oldLeftArrow !== leftArrow and oldSizes !== sizes) {
setArrowStyle(styling)
}
}, [rightArrow, leftArrow, sizes])
I think the reason of your delay is necessary here since you calculate based on rectangles of the first and the last element which are affected when you click on button and do animation of scrolling 500ms. So as a result your calculation needs to wait for animation to be done. change the number of animation and delay you will see the relation.
the style I meant.
#include transition(all 500ms ease);
In short, I think what you are using is the right way as long as you have animations related to the calculation.
setState takes an optional second argument which is a callback that executes after the state has been updated and the component has been re-rendered.
Another option is the componentDidUpdate lifecycle method.

Snap.svg Load svg in order not available

I'm trying to get the (load in order) example to work. Here is my code.
I load snap.js and then my code in loadsvg.js it has my plugin. Then main.js with my code calling the function. I get a error in console that says "base.loadFilesDisplayOrdered is not a function". So it can't find it any help will be appreciated. Thanks
Snap.plugin( function( Snap, Element, Paper, global ) {
function addLoadedFrags( whichSVG, fragList, runWhenFinishedFunc ) { // This is called once all the loaded frags are complete
for( var count = 0; count < fragList.length; count++ ) {
myEl = whichSVG.append( fragList[ count ] );
}
runWhenFinishedFunc();
}
Paper.prototype.loadFilesDisplayOrdered = function( list, afterAllLoadedFunc, onEachElementLoadFunc ) {
var image, fragLoadedCount = 0, listLength = list.length, fragList = new Array(), whichSVG = this;
for( var count = 0; count < listLength; count++ ) {
(function() {
var whichEl = count,
fileName = list[ whichEl ],
image = Snap.load( fileName, function ( loadedFragment ) {
fragLoadedCount++;
onEachElementLoadFunc( loadedFragment, fileName );
fragList[ whichEl ] = loadedFragment;
if( fragLoadedCount >= listLength ) {
addLoadedFrags( whichSVG, fragList, afterAllLoadedFunc );
}
} );
})();
}
};
});
Then i call it in main.js
var base = Snap("#svgout");
console.log(base);
var myLoadList = [ "svgs/layer.svg", "svgs/cutout.svg" ];
var myDisplayList = { "Bird.svg": "zoom", "Dreaming_tux.svg": "fade" };
base.loadFilesDisplayOrdered( myLoadList, onAllLoaded, onEachLoaded );
The problem is, you are trying to create Snap into a div element. Snap only works on SVG elements.
Change,
<div id="svgout"></div>
to
<svg id="svgout"></svg>
And the error should go away.
jsfiddle

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