상세 컨텐츠

본문 제목

[JavaScript] Html5, Canvas 폰트URL. 외부폰트 로드 관련.

WEB/JavaScript

by AlrepondTech 2018. 5. 14. 12:20

본문

반응형
728x170

 

 

 

=================================

=================================

=================================

 

 

 

 

 

 

 

 

 

출처: https://stackoverflow.com/questions/21635687/using-dom-to-create-font-face-with-style-tag-isnt-working-properly

 

 

I'm trying to initialize a style tag using the DOM with JavaScript and for some reason the code below doesn't want to work. Basically I have a div for a container (it's the id) and I want the p tag to display text on the div. So far I have this.

<html> <head> </head>  <style> body {           background-color: black;     } #container {            position: relative;      margin: 0 auto;          height: 100%;     width: 100%;     z-index: 1; } #p_1 {     font-family: my_custom;      font-size: 50px;        color: red;     z-index: 2; } </style> <script language = "JavaScript"> function initialize_font() {     var special_font = document.createElement("style");     special_font.type = "text/css";      document.body.insertBefore( special_font, container);     special_font.styleSheet.cssText = "@font-face {" + font-family: my_custom;  src: url('my_custom.TTF'); + "}";    } </script> <body onload = "initialize_font()">     <div id = "container">                              <p id = "p_1">hello</p>     </div>   </body> </html>

 

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

 

You've messed up the quotes and are not creating the style tag the correct way, and styles must be in the head section, and you don't have to wait for an onload event as there's no need for the DOM to be ready to insert the style tag.

Something more like this

<html>     <head>         <style type="text/css">             body {                       background-color: black;                 }             #container {                        position: relative;                  margin: 0 auto;                      height: 100%;                 width: 100%;                 z-index: 1;             }             #p_1 {                 font-family: my_custom;                  font-size: 50px;                    color: red;                 z-index: 2;             }         </style>         <script type="text/javascript">             var special_font = document.createElement("style");             special_font.type = "text/css";              special_font.innerHTML = "@font-face {font-family: my_custom;  src: url('my_custom.TTF');}";                document.getElementsByTagName('head')[0].appendChild(special_font);         </script>     </head>  <script> </script> <body>     <div id = "container">                              <p id = "p_1">hello</p>     </div>   </body> </html>

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

The <style> and the <script> must be inside the HEAD or the BODY

Here is the code and working example:

<html>     <head>     <style>         body {             background-color: black;         }         #container {             position: relative;             margin: 0 auto;             height: 100%;             width: 100%;             z-index: 1;         }         #p_1 {             font-family: my_custom;             font-size: 50px;             color: red;             z-index: 2;         }     </style>     <script type="text/javaScript">             var special_font = document.createElement("style");             special_font.type = "text/css";             document.body.insertBefore(special_font, container);             special_font.styleSheet.cssText = "@font-face {" + font - family: my_custom;             src: url('my_custom.TTF'); + "}";      </script>     </head>     <body>         <div id="container">             <p id="p_1">hello</p>         </div>     </body>  </html>

 

 

 

=================================

=================================

=================================

 

 

 

 

출처: https://stackoverflow.com/questions/29248182/how-do-i-put-custom-fonts-into-html5-canvas-easily

 

 

I'll discuss my code underneath. First off, My Javascript:

window.onload = function start() {             canvas = document.getElementById('canvas1');             C_Width = canvas.width;             C_Height = canvas.height;             cxt = canvas.getContext('2d');             setTimeout(text_handler,200);         }          function text_handler() {         console.log('made it!');         cxt.font="20px myFont";//font size and then font family.         cxt.fillStyle="white"; //color to be seen on a black canvas, default is black text         cxt.fillText("TEST",(C_Width/2-200),C_Height/2); //cxt.fillText("message",x_coord,y_coord);         }

Allow me to explain whats going on here. I have a simple window.onload function so that the canvas exists before I try to get its Id and Context. Inside my text_handler() function, I have the font size and the font family defined in one line, as well as my font color (White because I have a black canvas). Then in the canvas I draw my message, and provide an x coordinate and a y coordinate. The setTimeout(); delay may be necessary in order to give the canvas time to load the font. In the test program I wrote, I actually got the delay time down really low, though 100ms is almost unnoticeable. Another critical part of this is the CSS stylesheet:

canvas {             background-color: black; //for white text             font-family:myFont; //necessary         }         #load {             font-family:myFont; //necessary to load font with div             visibility: hidden; //makes div invisible but the div element forces the text to load before the canvas.             height: 0px;         }         @font-face {             font-family:myFont;              src: url('./Font_Path.ttf');             } //self-explanatory

I have of course defined the font in the canvas, the body of the webpage, and a necessary hidden div. The div helps load the font. I have styles in order that the div remains invisible but it still does its job. For some reason, through my testing, I determined that the font-family style must be above the other styles in my div. Of course, you could use whatever you want. Also of course, I use @font-face for my custom font.

Here's what the HTML looks like:

<body>     <div id="load">words</div> <!-- load font -->     <canvas id="canvas1" width="500px" height="500px"></canvas> </body>

As explained above, the div is necessary to load the font before the canvas can implement it. That's why I have "words" inside it.

I really hope this helps someone out because I simply couldn't find anything on it. Please ask me questions, tell me what I could have done differently in the comment section below, or just simply ways I can simplify my code. I'd appreciate the help and constructive criticism. Thanks, and happy Canvas-ing...

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

Although it doesn't have complete support yet you can now use the FontFace API to explicitly load fonts before using them on a canvas.

var f = new FontFace('Font name', 'url(/path/to/font.ttf)');  f.load().then(function() {    // Ready to use the font in a canvas context   console.log('font ready');    ctx.font = '48px Font name';   ctx.strokeText('Hello world', 100, 100);  });

I can confirm that this works on Chrome 61.0.3163.100, Safari 11.0 (12604.1.38.1.7), Firefox 56.0 (all OSX) and Safari iOS 11.1.

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

An important point that might get lost is that each font that is used on canvas must also be loaded by setting the font-family style-attribute for the canvas element.

Here's my version using jquery. The ready event removes the need for any timeouts.

<head>  <script src="jquery-3.3.1.min.js"></script>   <style>     @font-face {       font-family: 'AlexBrush';       src: url('fonts/AlexBrush-Regular.ttf');     }     @font-face {       font-family: 'Pacifico';       src: url('fonts/Pacifico.ttf');     }   </style> </head> <body>   <canvas id='testCanvas' width='1200px' height='800px'></canvas>   <script>     $(document).ready(function()     {         $('#testCanvas').css('font-family', "AlexBrush");         $('#testCanvas').css('font-family', "Pacifico");         var ctx = c.getContext("2d");         ctx.fillStyle = "#000";         ctx.font = "100px AlexBrush";         ctx.fillText('Hello World', 100, 300);         ctx.font = "100px Pacifico";         ctx.fillText('Hello World', 100, 500);     })   </script> </body>

 

 

 

=================================

=================================

=================================

 

 

 

출처: https://stackoverflow.com/questions/26110959/p5-js-loadfont-function

 

 

 

How can I change the font in p5.js? It does not recognize the Processing term "loadFont," does not carry over a font from CSS, nor does it let me put in a .vlw file or link to a GoogleFont. At least, not in any way I have tried.

The references page only contains "text" and "textFont" options (in the Typography section at the end of the p5.js references page), neither of which allow for actually specifying a font.

I have also tried the

text.style('font-family', 'Walter Turncoat');

option listed here (https://github.com/lmccart/p5.js/wiki/Beyond-the-canvas) to no avail. It actually broke the whole page. In CSS:

@font-face {     font-family: 'Walter Turncoat';     src: url('http://fonts.googleapis.com/css?family=Walter+Turncoat'); }

Processing version did not work:

var type = loadFont("AmericanTypewriter-48.vlw"); var smallType = loadFont("AmericanTypewriter-14.vlw");

Also,

var type = "Helvetica"; 

which they have in the examples for text and textFont does not work.

There has to be a way to have another font. Please help!

 

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

The examples given in the reference work fine. Run code snippet below for results. What do you mean when you say it doesn't work for you?

 

function setup() {   createCanvas(640, 480); }  function draw() {   fill(0);   textSize(36);   textFont("Georgia");   text("Hello World! in Georgia.", 12, 40);   textFont("Arial");   text("Hello World! in Arial.", 12, 100);   textFont("Walter Turncoat");   text("Hello World! in Walter Turncoat.", 12, 160); }
<link href="http://fonts.googleapis.com/css?family=Walter+Turncoat&.css" rel="stylesheet"/> <script src="http://cdn.jsdelivr.net/p5.js/0.3.8/p5.min.js"></script>

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

To load a font in p5.js you need a .ttf or .otf file, p5 doesn't work with .vlw files. So to use a font in p5 you need to:

  1. Get a .ttf or .otf font file. This font file will be loaded on execution time to your app.
  2. Declare a global variable to keep the font.
  3. Load the font with loadFont in a preload function.
  4. After the font is loaded you must use textFont() to tell p5 that this is the font to be used.
  5. Print someting with text().

Here is an example:

var myFont, fontReady = false;  function fontRead(){     fontReady = true; }  function preload() {     myFont = loadFont("./fonts/MyfontFile.ttf", fontRead); }  function setup() {     createCanvas(720, 400);     doyourSetup(); }  function draw() {     background(255);     if (fontReady) {         textFont(myFont);         text("Hello World!", 10, 30);     } }

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

According to the docs, if you have a font file that p5 recognizes (such as otf, ttf ect...), you can load that font file and than use it with the following 2 lines of code:

var myFont = loadFont('customfont.ttf'); textFont(myFont);

and then write with the font like this:

text('Stack overflow', 2,2);

 

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

You need to load the font in preload:

var font;  function preload() {     font = loadFont('thefont.ttf'); }  function setup() {     createCanvas(600, 400);     textFont(font); }  function draw() {     background(255);     text('The Text', 280, 300); }

 

 

 

=================================

=================================

=================================

 

 

 

반응형
그리드형


관련글 더보기

댓글 영역