Using Google Fonts with Shadow DOM [duplicate] - html

This question already has answers here:
Google Fonts Font Doesn't load
(6 answers)
Closed 3 years ago.
I'm trying to use a google font with my extension on the content script side - the Noto font I have downloaded and loading from the extension directory works (it is also declared in web_accessible_resources) and works fine in the ShadowDOM but the google font doesn't
I'm injecting this style text into the head:
var styleNode = document.createElement("style");
styleNode.type = "text/css";
styleNode.textContent =
"#font-face { font-family: Noto Serif; src: url('" +
browser.extension.getURL("NotoSerifCJKjp-SemiBold.otf") +
"') format('opentype'); } #font-face { font-family: Poppins; font-style: normal; font-weight: 400; src: url(https://fonts.gstatic.com/s/poppins/v6/pxiEyp8kv8JHgFVrJJbecmNE.woff2) format('woff2'); }";
document.head.appendChild(styleNode);
I also tried putting
#import url("https://fonts.googleapis.com/css?family=Poppins");
in the shadow dom style but that didn't work either

Adding the fonts as a link worked, no idea why:
var linkNode = document.createElement("link");
linkNode.type = "text/css";
linkNode.rel = "stylesheet";
linkNode.href = "//fonts.googleapis.com/css?family=Poppins";
document.head.appendChild(linkNode);
also can be done like this:
<link href="//fonts.googleapis.com/css?family=PT+Sans" rel="stylesheet" type="text/css">
as per Google Fonts Font Doesn't load

Related

use custom fonts in tilemill?

It seems like this can be done... but all the suggestions I've seen online aren't working for me. I have a customFont.ttf tile that I'm putting in this dir: 'home/greg/Documents/MapBox/project/myproject/customFont.ttf'
Then I'm using this code:
Map { font-directory: url(customFont.ttf); }
or
Map { font-directory: url(''); }
or
Map { font-directory: url(fonts/customFont.ttf); }
but nothing is working. I just get en error message such as:
"Invalid value for text-face-name, the type font is expected. comicSansMs, Arial Regular (of type string) was given. (line 71)"
any tips?
place your fonts in the folder app/assets/fonts, lib/assets/fonts or vendor/assets/fonts
If Rails 4+, you can only place your fonts in the folder app/assets/fonts.
In css:
#font-face {
font-family: 'customFont';
src:url('customFont.ttf');
font-weight: normal;
font-style: normal;
}

iTextSharp HTML to PDF conversion - unable to change font

I'm creating some PDF documents with iTextSharp (5.5.7.0) from HTML in ASP.NET MVC5 application, but I'm unable to change the font. I've tried almost everything that I was able to find on SO or from some other resources.
Code for PDF generation is as follows:
public Byte[] GetRecordsPdf(RecordsViewModel model)
{
var viewPath = "~/Template/RecordTemplate.cshtml";
var renderedReport = RenderViewToString(viewPath, model);
FontFactory.RegisterDirectory(Environment.GetFolderPath(Environment.SpecialFolder.Fonts));
using (var ms = new MemoryStream())
{
using (var doc = new Document())
{
doc.SetPageSize(PageSize.A4.Rotate());
using (var writer = PdfWriter.GetInstance(doc, ms))
{
doc.Open();
using (var html = new MemoryStream(Encoding.Default.GetBytes(renderedReport)))
{
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, html, Encoding.Default);
}
doc.Close();
}
}
var bytes = ms.ToArray();
return bytes;
}
}
Actual HTML is contained in renderedReport string variable (I have strongly typed .cshtml file which I render using MVC Razor engine and then return HTML in string).
I've tried to register some specific fonts, but that didn't help. I've also tried to register all fonts on my machine (as shown in example above), but that also didn't help. The fonts were loaded I've checked that in debug mode.
CSS is embedded in HTML file (in heading, style tag) like this:
body {
font-size: 7px;
font-family: Comic Sans MS;
}
(for test, I've decided to use Comic Sans, because I can recognize it with ease, I'm more interested in Arial Unicode MS actually).
And I'm actually able to change the font with that font-family attribute from CSS, but only from fonts that are preloaded by iTextSharp by default - Times New Roman, Arial, Courier, and some other (Helvetica i think). When I change it to - Comic Sans, or some other that is not preloaded iTextSharp renders with default font (Arial I would say).
The reason why I need to change the font is because I have some Croatian characters in my rendered HTML (ČĆŠĐŽčćšđž) which are missing from PDF, and currently I think the main reason is - font.
What am I missing?
A couple of things to make this work.
First, XMLWorkerHelper doesn't use FontFactory by default, you need to use one of the overloads to ParseXHtml() that takes an IFontProvider. Both of those overloads require that you specify a Stream for a CSS file but you can just pass null if your CSS lives inside your HTML file. Luckily FontFactory has a static property that implements this that you can use called FontFactory.FontImp
// **This guy**
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msHTML, null, Encoding.UTF8, FontFactory.FontImp);
Second, I know that you said that you tried registering your entire font directory out of desperation but that can be a rather expensive call. If you can, always try to just register the fonts you need. Although optional, I also strongly recommend that you explicitly define the font's alias because fonts can have several names and they're not always what we think.
FontFactory.Register(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "comic.ttf"), "Comic Sans MS");
Third, and this might not affect you, but any tags not present in the HTML, even if they're logically implied, won't get styling applied to them from CSS. That sounds weird so to say it differently, if your HTML is just <p>Hello</p> and your CSS is body{font-size: 7px;}, the font size won't get applied because your HTML is missing the <body> tag.
Fourth, and this is optional, but usually its easier to specify your HTML and CSS separately from each other which I'll do in the example below.
Your code was 95% there so with just a couple of tweaks it should work. Instead of a view I'm just parsing raw HTML and CSS but you can modify as needed. Please do remember (and I think you know this) that iTextSharp cannot process ASP.Net, only HTML, so you need to make sure that your ASP.Net to HTML conversion process is sane.
//Sample HTML and CSS
var html = #"<body><p>Sva ljudska bića rađaju se slobodna i jednaka u dostojanstvu i pravima. Ona su obdarena razumom i sviješću i trebaju jedna prema drugima postupati u duhu bratstva.</p></body>";
var css = "body{font-size: 7px; font-family: Comic Sans MS;}";
//Register a single font
FontFactory.Register(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "comic.ttf"), "Comic Sans MS");
//Placeholder variable for later
Byte[] bytes;
using (var ms = new MemoryStream()) {
using (var doc = new Document()) {
doc.SetPageSize(PageSize.A4.Rotate());
using (var writer = PdfWriter.GetInstance(doc, ms)) {
doc.Open();
//Get a stream of our HTML
using (var msHTML = new MemoryStream(Encoding.UTF8.GetBytes(html))) {
//Get a stream of our CSS
using (var msCSS = new MemoryStream(Encoding.UTF8.GetBytes(css))) {
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msHTML, msCSS, Encoding.UTF8, FontFactory.FontImp);
}
}
doc.Close();
}
}
bytes = ms.ToArray();
}

how to know format of fonts [duplicate]

This question already has answers here:
How to add some non-standard font to a website?
(21 answers)
Closed 9 years ago.
I am going to use #font-face. So I copied corbel font to my directory and there it shows 4 fonts CORBEL_0.TTF , CORBELB_0.TTF , CORBELI_0.TTF , CORBELZ_0.TTF and next I copied Kozuka Gothic Pro font to my directory and there it shows 6 fonts KozGoPro-Bold.otf , KozGoPro-ExtraLight.otf , KozGoPro-Heavy.otf , KozGoPro-Light.otf , KozGoPro-Medium.otf , KozGoPro-Regular.otf
How to write src using #font-face rule?
As in example url("../../css/fonts/League_Gothic.eot") format('eot'); the format eot , is it the extension of font? Anyone give me the idea for full syntax within #font-face.
#font-face
{
font-family: corbel;
src: url('/fonts/corbel.ttf'),
url('/fonts/corbel.eot');
}
#font-face
{
font-family: Kozuka;
src: url('/fonts/Kozuka.ttf'),
url('/fonts/Kozuka.eot');
}
Like this:
#font-face {
font-family: 'Kozuka Gothic Pro';
src: url("../../css/fonts/Kozuka Gothic Pro.otf") format('truetype');
src: local("☺"),
url("../../css/fonts/KozGoPro-Bold.otf"),
url("../../css/fonts/KozGoPro-ExtraLight.otf") format('truetype'),
url("../../css/fonts/KozGoPro-Heavy.otf") format('truetype'),
url("../../css/fonts/KozGoPro-Light.otf") format('truetype');
url("../../css/fonts/KozGoPro-Medium.otf") format('truetype')
url("../../css/fonts/KozGoPro-Regular.otf") format('truetype');
}

Drawing text to <canvas> with #font-face does not work at the first time

When I draw a text in a canvas with a typeface that is loaded via #font-face, the text doesn't show correctly. It doesn't show at all (in Chrome 13 and Firefox 5), or the typeface is wrong (Opera 11). This type of unexpected behavior occurs only at the first drawing with the typeface. After then everything works fine.
Is it the standard behavior or something?
Thank you.
PS: Following is the source code of the test case
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>#font-face and <canvas></title>
<style id="css">
#font-face {
font-family: 'Press Start 2P';
src: url('fonts/PressStart2P.ttf');
}
</style>
<style>
canvas, pre {
border: 1px solid black;
padding: 0 1em;
}
</style>
</head>
<body>
<h1>#font-face and <canvas></h1>
<p>
Description: click the button several times, and you will see the problem.
The first line won't show at all, or with a wrong typeface even if it does.
<strong>If you have visited this page before, you may have to refresh (or reload) it.</strong>
</p>
<p>
<button id="draw">#draw</button>
</p>
<p>
<canvas width="250" height="250">
Your browser does not support the CANVAS element.
Try the latest Firefox, Google Chrome, Safari or Opera.
</canvas>
</p>
<h2>#font-face</h2>
<pre id="view-css"></pre>
<h2>Script</h2>
<pre id="view-script"></pre>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script id="script">
var x = 30,
y = 10;
$('#draw').click(function () {
var canvas = $('canvas')[0],
ctx = canvas.getContext('2d');
ctx.font = '12px "Press Start 2P"';
ctx.fillStyle = '#000';
ctx.fillText('Hello, world!', x, y += 20);
ctx.fillRect(x - 20, y - 10, 10, 10);
});
</script>
<script>
$('#view-css').text($('#css').text());
$('#view-script').text($('#script').text());
</script>
</body>
</html>
Drawing on canvas has to happen and return immediately when you call the fillText method. However, the browser has not yet loaded the font from the network, which is a background task. So it has to fall back to the font it does have available.
If you want to make sure the font is available, have some other element on the page preload it, eg.:
<div style="font-family: PressStart;">.</div>
Use this trick and bind an onerror event to an Image element.
Demo here: works on the latest Chrome.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'http://fonts.googleapis.com/css?family=Vast+Shadow';
document.getElementsByTagName('head')[0].appendChild(link);
// Trick from https://stackoverflow.com/questions/2635814/
var image = new Image();
image.src = link.href;
image.onerror = function() {
ctx.font = '50px "Vast Shadow"';
ctx.textBaseline = 'top';
ctx.fillText('Hello!', 20, 10);
};
You can load fonts with the FontFace API before using it in the canvas:
const myFont = new FontFace('My Font', 'url(https://myfont.woff2)');
myFont.load().then((font) => {
document.fonts.add(font);
console.log('Font loaded');
});
The font resource myfont.woff2 is first downloaded. Once the download completes, the font is added to the document's FontFaceSet.
The specification of the FontFace API is a working draft at the time of this writing. See browser compatibility table here.
The nub of the problem is that you are trying to use the font but the browser has not loaded it yet and possibly has not even requested it. What you need is something that will load the font and give you a callback once it is loaded; once you get the callback, you know it is okay to use the font.
Look at Google's WebFont Loader; it seems like a "custom" provider and an active callback after the load would make it work.
I've never used it before, but from a quick scan of the docs you need to make a css file fonts/pressstart2p.css, like this:
#font-face {
font-family: 'Press Start 2P';
font-style: normal;
font-weight: normal;
src: local('Press Start 2P'), url('http://lemon-factory.net/reproduce/fonts/Press Start 2P.ttf') format('ttf');
}
Then add the following JS:
WebFontConfig = {
custom: { families: ['Press Start 2P'],
urls: [ 'http://lemon-factory.net/reproduce/fonts/pressstart2p.css']},
active: function() {
/* code to execute once all font families are loaded */
console.log(" I sure hope my font is loaded now. ");
}
};
(function() {
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
'://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})();
What about using simple CSS to hide a div using the font like this:
CSS:
#preloadfont {
font-family: YourFont;
opacity:0;
height:0;
width:0;
display:inline-block;
}
HTML:
<body>
<div id="preloadfont">.</div>
<canvas id="yourcanvas"></canvas>
...
</body>
https://drafts.csswg.org/css-font-loading/
var myFont = new FontFace('My Font', 'url(https://myfont.woff2)');
myFont.load().then(function(font){
// with canvas, if this is ommited won't work
document.fonts.add(font);
console.log('Font loaded');
});
i've bumped into the issue when playing with it recently http://people.opera.com/patrickl/experiments/canvas/scroller/
worked around it by adding the font-family to canvas directly in the CSS, so you can just add
canvas { font-family: PressStart; }
This article sorted out my issues with lazy loaded fonts not being displayed.
How to load web fonts to avoid performance issues and speed up page loading
This helped me ...
<link rel="preload" as="font" href="assets/fonts/Maki2/fontmaki2.css" rel="stylesheet" crossorigin="anonymous">
Since I've not found any example of the actual FontFace usage, here's #Fred
Fred Bergman's answer, slightly modified
const fontUrl = 'https://fonts.gstatic.com/s/robotomono/v22/L0xuDF4xlVMF-BfR8bXMIhJHg45mwgGEFl0_Of2_ROW-AJi8SJQt.woff'
const robotoFont = new FontFace('Roboto Mono', `url(${fontUrl})`);
// Canvas variables
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
robotoFont.load().then((font: FontFace) => {
// This is required
document.fonts.add(font);
// Usage example
ctx.font = `30px '${font.family}'`;
ctx.fillText("Hello World!", 10, 50);
});
Here's the compatibility table
If you want to redraw everytime a new font is loaded (and probably change the rendering) the font loading api has a nice event for that, too. I had problems with the Promise in a complete dynamic environment.
var fontFaceSet = document.fonts;
if (fontFaceSet && fontFaceSet.addEventListener) {
fontFaceSet.addEventListener('loadingdone', function () {
// Redraw something
});
} else {
// no fallback is possible without this API as a font files download can be triggered
// at any time when a new glyph is rendered on screen
}
I am not sure if this will help you, but to solve the problem with my code I simply created a for loop at the top of my Javascript which ran through all the fonts that I wanted to load. I then ran a function to clear the canvas and preload the items I wanted on the canvas. So far it has worked perfectly. That was my logic I have posted my code below:
var fontLibrary = ["Acme","Aladin","Amarante","Belgrano","CantoraOne","Capriola","CevicheOne","Chango","ChelaOne","CherryCreamSoda",
"ConcertOne","Condiment","Damion","Devonshire","FugazOne","GermaniaOne","GorditasBold","GorditasRegular",
"KaushanScript","LeckerliOne","Lemon","LilitaOne","LuckiestGuy","Molle","MrDafoe","MrsSheppards",
"Norican","OriginalSurfer","OswaldBold","OswaldLight","OswaldRegular","Pacifico","Paprika","Playball",
"Quando","Ranchers","SansitaOne","SpicyRice","TitanOne","Yellowtail","Yesteryear"];
for (var i=0; i < fontLibrary.length; i++) {
context.fillText("Sample",250,50);
context.font="34px " + fontLibrary[i];
}
changefontType();
function changefontType() {
selfonttype = $("#selfontype").val();
inputtextgo1();
}
function inputtextgo1() {
var y = 50;
var lineHeight = 36;
area1text = document.getElementById("bag1areatext").value;
context.clearRect(0, 0, 500, 95)
context.drawImage(section1backgroundimage, 0, 0);
context.font="34px " + selfonttype;
context.fillStyle = seltextcolor;
context.fillText(area1text, 250, y);
}
I wrote a jsfiddle incorporating most of the suggested fixes here but none resolved the issue. However, I am a novice programmer so perhaps did not code the suggested fixes correctly:
http://jsfiddle.net/HatHead/GcxQ9/23/
HTML:
<!-- you need to empty your browser cache and do a hard reload EVERYTIME to test this otherwise it will appear to working when, in fact, it isn't -->
<h1>Title Font</h1>
<p>Paragraph font...</p>
<canvas id="myCanvas" width="740" height="400"></canvas>
CSS:
#import url(http://fonts.googleapis.com/css?family=Architects+Daughter);
#import url(http://fonts.googleapis.com/css?family=Rock+Salt);
canvas {
font-family:'Rock Salt', 'Architects Daughter'
}
.wf-loading p {
font-family: serif
}
.wf-inactive p {
font-family: serif
}
.wf-active p {
font-family:'Architects Daughter', serif;
font-size: 24px;
font-weight: bold;
}
.wf-loading h1 {
font-family: serif;
font-weight: 400;
font-size: 42px
}
.wf-inactive h1 {
font-family: serif;
font-weight: 400;
font-size: 42px
}
.wf-active h1 {
font-family:'Rock Salt', serif;
font-weight: 400;
font-size: 42px;
}
JS:
// do the Google Font Loader stuff....
WebFontConfig = {
google: {
families: ['Architects Daughter', 'Rock Salt']
}
};
(function () {
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
'://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})();
//play with the milliseconds delay to find the threshold - don't forget to empty your browser cache and do a hard reload!
setTimeout(WriteCanvasText, 0);
function WriteCanvasText() {
// write some text to the canvas
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.font = "normal" + " " + "normal" + " " + "bold" + " " + "42px" + " " + "Rock Salt";
context.fillStyle = "#d50";
context.fillText("Canvas Title", 5, 100);
context.font = "normal" + " " + "normal" + " " + "bold" + " " + "24px" + " " + "Architects Daughter";
context.fillText("Here is some text on the canvas...", 5, 180);
}
Workaround
I eventually gave in and, on the first load, used an image of the text while also positioning the text with the font-faces outside of the canvas display area. All subsequent displays of the font-faces within the canvas display area worked no problem. This is not an elegant workaround by any means.
The solution is baked into my website but if anyone needs I will try to create a jsfiddle to demonstrate.
Some browsers support the CSS Font Loading specification. It allows you to register register a callback for when all the fonts have been loaded. You can delay drawing your canvas (or at least drawing text into your canvas) until then, and trigger a redraw once the font is available.
The canvas is drawn independently of the DOM loading. The preload technique will only work if the canvas is drawn after the preload.
My solution, even if it is not the best:
CSS:
.preloadFont {
font-family: 'Audiowide', Impact, Charcoal, sans-serif, cursive;
font-size: 0;
position: absolute;
visibility: hidden;
}
HTML:
<body onload="init()">
<div class="preloadFont">.</div>
<canvas id="yourCanvas"></canvas>
</body>
JavaScript:
function init() {
myCanvas.draw();
}
I try to use FontFaceSet.load to fix the problem:
https://jsfiddle.net/wengshenshun/gr1zkvtq/30
const prepareFontLoad = (fontList) => Promise.all(fontList.map(font => document.fonts.load(font)))
You can find the browser compatibility from https://developer.mozilla.org/en-US/docs/Web/API/FontFaceSet/load
First of all use Google's Web Font loader as was advised in the other answer and add your drawing code to the callback it provides to indicate the fonts have been loaded. However this is not the end of the story. From this point it is very browser dependent. Most of the time it will work fine, but sometimes it may be required to wait for couple hundreds of milliseconds or use the fonts somewhere else on the page. I tried different options and the one method that afaik always works is to quickly draw some test messages in the canvas with the font family and font size combinations that you are going to use. You can do it with the same color as background, so they won't even be visible and it will happen very fast. After that fonts always worked for me and in all browsers.
My answer addresses Google Web fonts rather than #font-face. I searched everywhere for a solution to the problem of the font not showing up in the canvas. I tried timers, setInterval, font-delay libraries, and all kinds of tricks. Nothing worked. (Including putting font-family in the CSS for canvas or the ID of the canvas element.)
However, I found that animating text rendered in a Google font worked easily. What's the difference? In canvas animation, we re-draw the animated items again and again. So I got the idea to render the text twice.
That did not work either -- until I also added a short (100ms) timer delay. I've only tested on a Mac so far. Chrome worked fine at 100ms. Safari required a page reload, so I increased the timer to 1000, and then it was fine. Firefox 18.0.2 and 20.0 wouldn't load anything on the canvas if I was using Google fonts (including the animation version).
Full code: http://www.macloo.com/examples/canvas/canvas10.html
http://www.macloo.com/examples/canvas/scripts/canvas10.js
Faces same problem. After reading "bobince" and others comments, I uses following javascript to workaround it :
$('body').append("<div id='loadfont' style='font-family: myfont;'>.</div>");
$('#loadfont').remove();
Add a delay as below
<script>
var c = document.getElementById('myCanvas');
var ctx = c.getContext('2d');
setTimeout(function() {
ctx.font = "24px 'Proxy6'"; // uninstalled #fontface font style
ctx.textBaseline = 'top';
ctx.fillText('What!', 20, 10);
}, 100);
</script>

How can I use custom fonts in an HTML5 Canvas element?

I've looked at things like Cufon and typeface.js but they seem to be SIFR alternatives and don't allow you to set freeform coordinates and draw custom type onto a <canvas>
Anyone got any ideas?
I've thrown together a simple demo on jsfiddle here showing how to do this with #font-face: http://jsfiddle.net/zMKge/
Opera also has a simple tutorial on using <canvas>, including the text API.
CSS:
#font-face {
font-family: 'KulminoituvaRegular';
src: url('http://www.miketaylr.com/f/kulminoituva.ttf');
}
Javascript:
var ctx = document.getElementById('c').getContext('2d');
var kitty = new Image();
kitty.src = 'http://i954.photobucket.com/albums/ae30/rte148/891blog_keyboard_cat.gif';
kitty.onload = function(){
ctx.drawImage(this, 0,0,this.width, this.height);
ctx.font = '68px KulminoituvaRegular';
ctx.fillStyle = 'orangered';
ctx.textBaseline = 'top';
ctx.fillText ('Keyboard Cat', 0, 270);
};
I have just answered this question here: Preload font HTML5, JS, Kinetic.js?
The essential part:
#font-face {
font-family: 'myfont';
src: url('myfont.eot');
src: url('myfont.eot?#iefix') format('embedded-opentype'),
url('myfont.woff') format('woff'),
url('myfont.ttf') format('truetype'),
url('myfont.svg#myfont') format('svg');
font-weight: normal;
font-style: normal;
}
It should not matter if you are using KineticJS or not, the only difference without KineticJS is that you would possibly create the Canvas element directly with HTML instead of using a div layer as container. After all KineticJS just creates a normal Canvas element in that container.
an answer from 3 years into the future lol
you can user javascript's new FontFace(family, font, descriptor)
https://developer.mozilla.org/en-US/docs/Web/API/FontFace/FontFace
where family is the name of the font, font is a url or ttf binary data, and descriptor is css elements.
then use ctx.fillText() to create the text