What is the process for creating text within a rectangle using canvas, pixi.js, or three.js?

I've been tasked with creating a dynamic progress bar that shows the time remaining until a specific date. While I've successfully implemented the countdown feature, I'm now faced with the challenge of making the numbers fill in a specified outline as the time decreases. I am looking for a solution using a blank canvas, or potentially leveraging three.js or pixi.js for this task. Here is a screenshot illustrating the concept.

Answer №1

To achieve this effect, one can utilize SVG in conjunction with a small snippet of JavaScript code. Utilizing a linear-gradient that essentially acts as a sharp step allows for filling the text dynamically.

Here is a functional example:

const userInput = document.querySelector("input");
const gradientStopsArray = Array.from(
  document.querySelectorAll("#fillGradient stop")
);

userInput.addEventListener("input", event => {
  const sliderValue = event.target.valueAsNumber;
  gradientStopsArray.forEach(stopItem => {
    stopItem.offset.baseVal = sliderValue;
  });
});
body { margin: 0; background: red; font-family: sans-serif; }
svg { width: 100%; height: auto; color: white; }
svg text {
  font-size: 60px;
  font-weight: bold;
  stroke: currentColor;
  stroke-width: 1px;
  fill: url(#fillGradient);
}
input { position: fixed; bottom: 1em; display: block; width: 90%; margin: 0 5%; }
<svg viewBox="0 0 400 200">
  <defs>
    <linearGradient id="fillGradient">
      <stop offset="50%" stop-color="currentColor" />
      <stop offset="50%" stop-color="transparent" />
    </linearGradient>
   </defs>

  <text x="0" y="60">10D:20:42:12</text>
</svg>

<input type="range" min=0 max=1 step=0.001 />

If a canvas-based approach is preferred, a simple method could involve:

  • Rendering the text with a white stroke and fill
  • Using clearRect to erase a portion of the text
  • Re-rendering the text with a transparent fill

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

how to put an end to sequential animations in React Native

Is there a way to pause a sequenced animation triggered by button A using button B? Thank you for your help! ...

Verify if a string contains a digit higher than one

I am struggling with extracting numbers from a string that may contain numbers and converting them into a comma-separated value. var stringOne = "Returned 12 string"; var extractNum = "1,2" After successfully extracting the numbers, I need to check if a ...

What is the method for inputting multi-line strings in the REST Client extension for Visual Studio Code?

Clarification There seems to be some confusion regarding the nature of the data I am storing. I am developing a code snippet web application using Express.js and MongoDB. The purpose is not to store executable code for later use; instead, I am saving snipp ...

JavaScript 'Post' Request Triggered an Error

I've been encountering a "Bad Request" error while attempting to make a POST request. I would greatly appreciate it if someone could point out where I may have gone wrong. function mkSentiTopics() { dta['n_clusters'] = 3; $.ajax({ ...

Issue with overflowX:visible not functioning properly in react-infinite-scroll-component

After implementing the infinite scroll using the second method, I encountered an issue where the content I was displaying had overflow on width/x. I attempted to override the infinite scroll style with overflowX:visible, but unfortunately, it did not work. ...

What are the methods to alter validation for a Formfield based on the input from other Formfields?

My aim is to create a Form where input fields are required only if one or more of them are filled out. If none of the fields have been filled, then no field should be mandatory. I came across a suggestion on a website that recommended using "valueChanges" ...

choose the text following a specific section within the class attribute of an element

In my code, I am trying to extract a number from an input text element using the jQuery method find. The class name of the input text contains a variable number denoted as x, following the substring page-id. Here is the approach I have taken: var id = ui ...

Cannot set value with document.getElementById() function

Here is the code snippet that seems to be causing an issue: <h1 id="test">15</h1> setTimeout(() => { console.log("awesome"); document.getElementById("test").value = 10; }, 2000); Even though awesome ge ...

Wrap the content with a div at the beginning and at the end

Hello, I am currently working on implementing the following structure: <div class="content"> <img src="/"> <img src="/"> <div class="slideshow"> <img src="/"><img src="/"><img src="/"></div> ...

Stop the annoying page flicker in Next.js 12 by implementing a custom dark mode using Tailwind CSS classes

Is there a way to prevent the page flash when implementing dark mode in Tailwind CSS using classes in Next.js v12 without relying on third-party packages like next-themes? I have explored different solutions: This StackOverflow Q&A How to fix dark mo ...

Retrieve the parameter values in PHP that were passed from AngularJS

This is my first time working with PHP and AngularJS. I am trying to pass parameters from AngularJS to a PHP file, where they will be used in an INSERT query. I have set up an XMLHttpRequest to call the PHP file (addsubscriber.php?par1=val1&par2=val2) ...

Guide on merging the root route with child routes using react router v6

When a user visits "/", I want it to automatically redirect them to "/todo", but this functionality is not working as expected. let router = createBrowserRouter([ { path: "/", element: <Layout />, children: ...

Encountering a Typescript error while attempting to extract state from a History object containing an enum property

My enum structure is as follows: enum values { first, second, } Within my component, I handle the history object like this: const { push, location: { state = {} } } = useHistory(); Additionally, in the same component within a useEffect hook, I have ...

Condense items into objects and arrays when the Express query yields multiple objects in a many-to-many query

I have a situation where my SQL queries are returning multiple objects due to a many-to-many mapping in express. I am in search of a tool that can help me simplify these common objects by nesting arrays of objects within them. SELECT * FROM User LEFT JOIN ...

Consistent surface appearance across combined mesh

Is there a way to texture a merged mesh from geometry as one solid piece rather than separately on each individual shape? In the provided code snippet, the textures are applied to separate geometries (refer to image points 1 and 2) - two Cubes and one Cyli ...

The MUI Select component requires two clicks to open its menu if another Select component's menu is already open

I have been developing an application with two dropdowns (Select components) positioned next to each other, denoted as A and B. When A is open and the user intends to click on B to open it, I observed that in the default behavior of material UI, the user ...

Activate Lottie animation upon scrolling

I recently created a unique lottie animation and successfully integrated it into my Nuxt project. I am now looking for the most effective way to manage the animation's behavior as the user scrolls through the page. I noticed that the component has an ...

NodeJS reports an invalid key length, while C# accepts the key length as valid

Currently, I am in the process of converting Rijndael decryption from C# to NodeJS. The Key (or Passphrase) being used is 13 characters long, while the IV used is 17 characters long. Note: The length choice for both Key and IV is beyond my control Disp ...

View the user's ID profile

Having trouble accessing user profiles? For example, as User 1, you want to view User 2's profile but when entering the URL (e.g. localhost/$userID), only information from your own profile (User 1) is displayed. Below is the HTML CODE for displaying ...

What steps can be taken to prevent double division within a loop?

Appreciate your assistance. This is the structure of my code: var CatItems = ""; for(var x=0; x < data.PRODUCTS.length; x++) { if (x % 3 === 0) CatItems += '<li class="jcarousel-item jcarousel-item-horizontal jcarousel-item-'+[x]+' ...