Issue with typography upon initial page load

Hey everyone! I recently completed a crash course in html, css, and javascript within just one month. However, I encountered an issue while using canvas to draw text with a custom font. The font didn't load the first time I ran the code, but strangely it worked fine after that initial hiccup. I tried troubleshooting but couldn't understand why this happened or how to fix it. Could anyone shed some light on what went wrong and provide a solution? Thank you. Below is the code snippet:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <style>
        @font-face { font-family: SuperLegendBoy; src: url('SuperLegendBoy-4w8Y.ttf'); }
    </style>
</head>
<body>
<canvas id="canvass" width="500" height="500" style="border: 1px solid black"></canvas>
</body>

</html>
<script>
    let canvas = document.getElementById("canvass");
    let ctx = canvas.getContext("2d");
    function drawText() {
        ctx.font = "25px SuperLegendBoy";
        ctx.fillText("hello", 200, 200);

    }
    drawText();

</script>

Answer №1

Using font-face correctly can be a bit tricky. Have you experimented with including format("woff"); at the end of the font-face "src" attribute?

Answer №2

What seems to be the issue?

The problem arises from the asynchronous loading of the font. This means that while the CSS @font-face rule initiates the loading process, it happens in the background. Consequently, when the font eventually finishes loading, it restyles all text elements using it.

In most cases this wouldn't be problematic, but if a <canvas> immediately converts text into pixel data, any changes in font styling won't be applied once the font loads.

Why did it work on the second attempt?

Browsers tend to cache resources, including fonts, allowing them to be stored locally and retrieved quickly without having to be re-downloaded. This cached version is readily available, ensuring smoother and faster rendering on subsequent visits.

How can this challenge be resolved?

To address this issue, ensure your JavaScript code responsible for canvas drawing is wrapped within an onload event listener. This listener will ensure that the script executes only after all resources, including fonts, have fully loaded:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <style>
        @font-face { font-family: SuperLegendBoy; src: url('SuperLegendBoy-4w8Y.ttf'); }
    </style>
</head>
<body>
<canvas id="canvass" width="500" height="500" style="border: 1px solid black"></canvas>
<script>
    let canvas = document.getElementById("canvass");
    let ctx = canvas.getContext("2d");
    function drawText() {
        ctx.font = "25px SuperLegendBoy";
        ctx.fillText("hello", 200, 200);

    }

    window.addEventListener('load', () => {
        drawText();
    })

</script>
<!-- The closing body and html tags might need adjustment (though not critical). Placing the script as the last element of body or utilizing the DOMContentLoaded event would enhance structure -->
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Show and hide a division based on the status of a checkbox

I have a specific requirement regarding authentication modes. When selecting a single factor, only one type of authentication mode can be chosen at a time and the corresponding div will be displayed. However, when selecting multiple factors, I should be ab ...

Encountering an error when trying to access a property of an undefined MVC model in a

Embarked on a journey to learn web service development, only to encounter a roadblock. I'm struggling to figure out how to utilize ExpressJS Router() to pass POST data to the controller files. Upon inspecting the request redirected from product.route. ...

Why won't the code for detecting the DEL key in a textarea work on my computer?

I've been trying to detect when a user presses the Delete key and came across this helpful tutorial here The code worked flawlessly on jsfiddle.net, you can check it out here- http://jsfiddle.net. However, when I copied the same code to my local comp ...

bringing in documents from a shared repository

Exploring the folder structure below: MainFolder ├──sourceFolder │ └──assetsFolder │ ├──GlobalStyles.js │ ├──colors.js │ ├──images.js │ ├──someOtherFile.js │ └──package.json <-- ...

Javascript text validation is malfunctioning as the alert message fails to appear

Looking for a simple form validation script: <script language=”javascript”> function checkForm(register) { if (""==document.forms.register.FNAME.value){ alert("Please fill out this field!"); document.forms.register.FNAME.focus( ...

Issues with Three.js raycaster intersectObjects

I am currently working on a 3D scatter plot where spheres are used to represent the points, and I am attempting to show information from the points when they are clicked. After researching various answers on this platform, I believe I am moving in the righ ...

The Bootstrap modal seems unable to bring the button back

Despite my code functioning properly, the button is not going backward after being clicked. Check out my output here <a href="#myModal" role="button" class="btn btn-large btn-primary" data-toggle="modal">Launch Demo Modal</a> Here is the HTML ...

Exploring the Concept of Class Inheritance in Javascript

I've been thinking about how to implement Class Inheritance in JavaScript. Since JavaScript doesn't have classes like other languages, we typically use functions to create objects and handle inheritance through Prototype objects. For instance, h ...

Utilize Bootstrap 4 to seamlessly switch between nav-pills for larger screens and navbar-nav for smaller screens

On larger screens, I prefer the appearance of the nav pills. However, once the collapse button appears, I would like the menu to stack and resemble the image provided instead of the pills. Do I require custom CSS to achieve this? <div id="menu" class=" ...

What is the best method for saving inert data in Vuex?

Once the VueJS application is initialized, I have certain data loaded on the page that will remain static until the HTML page is reloaded. This data is in the form of a nonReactiveObjectWithSomeNestedData example: const nonReactiveObjectWithSomeNestedData ...

The attempt to bring in the model using `require` has resulted in an error. The `require` method used here, in combination with `path.join`, does

As a beginner in web development, I have been working on a project using MySQL, Node.js with Express. However, I am encountering a TypeError issue when using Sequelize. Can anyone kindly explain this to me and assist me in finding a solution? "seque ...

Chrome is giving me trouble with the Select (dropdown) background image feature

Is it possible to set an image as the background for a select/drop-down menu? I've tried using the following CSS, which works in Firefox and IE but not in Chrome: #main .drop-down-loc { width:506px; height: 30px; border: none; background-color: Tr ...

Retrieving the image source from the image element by utilizing $(this).find("");

Currently facing a challenge in retrieving the image source (e.g., ./imgs/image.jpg) from an image element. Managed to make some progress by using the following code: var image = document.getElementById("home-our-doughnuts-box-image").getAttribute("src" ...

Having difficulty performing raycasting on a singular object within a group in three.js to trigger an animation

Having issues with raycasting into a group in my three.js project. The goal is to trigger animations using TweenMax on object click. However, the problem arises when clicking on an object with another object behind it, causing both animations to be trigge ...

Interacting with JSON API data in real-time using AJAX and the power of JQuery

I'm currently working on displaying data dynamically from an API, and everything is functioning well except for the "Next" and "Previous" links. I can't seem to get them to update the value count in the search bar. My problem lies in executing my ...

AngularJS redirection causes the previous template to quickly appear and then disappear

This particular question has been circulating without a satisfactory resolution for some time, so hopefully the information provided here will help clear up any confusion. Essentially, I have an object called resolve attached to my routes, set up like thi ...

Ensure that all elements with the :hover event have a text color of #fff in CSS

 Troubleshooting problems with block's child elements during the :hover event. Specifically, I have a pricing block where I want all texts to be of color #fff when hovered over. Currently, when hovering over the <h3> and <p> elements ...

Preserve the visibility of a text input form while the checkbox is selected

Within my HTML code, there is a form that includes a checkbox labeled "other." When this checkbox is selected, a textbox will appear. If the user types in text and submits the form, the textbox disappears, but the checkbox remains checked (as saved in loca ...

Tips for bringing a particular tab into focus when a page initially loads

My webpage features custom links (tabs) that display content when clicked. By default, the first tab is selected and its content is shown, while the rest are set to display:none. Clicking on any other link will assign the 'selected' class to it, ...

How can I prevent mouse movement hover effects from activating in a media query?

I have implemented a custom image hover effect for links in my text using mousemove. However, I want to disable this feature when a specific media query is reached and have the images simply serve as clickable links without the hover effect. I attempted ...