Is it possible to properly align a text string in p5.js?

I've come across some really impressive examples of kinetic typography multiple times. These examples treat every letter as a particle, creating a system where text can be influenced by forces like gravity or centrifugal force. Usually, these systems are built using Processing and p5.js.

Inspired by these dynamic typographic examples, I'm working on an interactive web screen filled with text using p5.js. When the user hovers their cursor over the text, it starts bouncing around the screen.

While translating my sketch from Processing to p5.js, I encountered an issue with the spacing of the text in the setup() function. The original code in Processing functions correctly, but in p5.js, the spacing is not as smooth.

Here's the section of code in Processing that focuses on spacing the letters:


void setup() {
 size(640, 360);
 f = createFont("Arial", fontS, true);
 textFont(f);
 springs = new Spring[message.length()]; 
 int locx = 40;
 int locy = 100;
 for (int i = 0; i < message.length(); i++) {
    springs[i] = new Spring(locx, locy, 40, springs, i, message.charAt(i)); 
    locx += textWidth(message.charAt(i));
    if (locx >= 360) {
        locy += 60;
        locx = 40;
    }
 }
}

You can view the result https://i.sstatic.net/Itnvx.png

In the translated p5.js code, I attempted to fix the spacing issue by adjusting the value of locx:

springs[i] = new Spring(locx*5, locy, 40, springs, i, message.charAt(i));

The updated result can be seen here: https://i.sstatic.net/FvuUJ.png. While it may seem correct visually, I am confident there is still an underlying problem.

I have tried various solutions, including modifying the Spring class and its related functions. Unfortunately, I haven't been able to resolve the spacing issue entirely. Any assistance would be greatly appreciated.

//Edit As suggested in the comments, here is the revised Spring class written in p5.js:

// Spring class
class Spring {
  constructor (_x, _y, _s, _others, _id, letter_) {
    // Initialization code...
  }

  update() {
    // Update logic...
  }

  overEvent() {
    // Mouse-over detection...
  }

  otherOver() {
    // Check other springs...
  }

  box_collision() {
    // Handling edge collisions...
  }

  collide() {
    // Collision handling...
  }

  display() {
    // Display method...
  }

  pressed() {
    // Handling click/touch events...
  }

  released() {
    // Handling release events...
  }
}

To access the full code and experiment with it further, visit the Spring text p5js code editor.

Please note that I made modifications to the Spring class structure, moving functions outside the constructor. However, I'm still struggling with fixing the spacing issue in my kinetic typography project.

Answer №1

I was able to fix the issue.

Upon further examination, it became clear that the code was accurate from the start.

What I overlooked during the process was that I needed to specify the font size in the function setup() in order for the text to be displayed correctly on the screen.

https://i.sstatic.net/ekA9Z.png

You can view the outcome by visiting the p5.js editor link I shared earlier.

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

After refreshing the page, the ngRoute white page is displayed

I've encountered an issue with my Angular website. I built it using ngRoute, but when I click on a link, a white page appears. Only after refreshing the page does the content actually show up. Even in the browser's DevTools, you can see the html ...

Utilize Reactjs to efficiently showcase a collection of arrays within an object

I am struggling with a JSON file that has nested dropdown mega menu levels and I can't figure out how to map and render multiple levels of arrays and objects to create a tree-like structure. Here is my current JSON Structure: { "megamenu": [ { ...

Guide to incorporating d.ts file for enhancing intellisense in VS Code using a method akin to the NPM approach

In my nodejs project (in JS), I find myself relying heavily on node global variables. Despite receiving warnings against using globals, everything works well except for one thing: The lack of intellisense for globals. Every time I need to use a global fu ...

Comparing SSE and Ajax Polling for querying in the browser without using JavaScript code

I have been learning about Server Side Events and one key distinction that stands out to me is the way SSE handles server queries compared to Ajax Polling. With Ajax Polling, users are responsible for querying the server after each response, whereas with S ...

The AngularJS ng-disabled directive does not seem to function properly when the input is $pristine, but it works as expected when the

I am attempting to prevent a materializecss button from being clickable if a specific input field in a form is empty. However, I have only been able to accomplish this successfully by using ng-disable when the form is $pristine, not on the individual input ...

Which kinds of scripting languages are commonly found on the client-side of browsers?

I have been researching client-side browser languages and experimenting with a few, but I feel like there may be more options out there that I'm not aware of. I am looking for a solution that can be easily processed either in the browser or on the cli ...

JavaScript vanilla can be difficult to grasp, especially when it comes to

I'm experiencing a delay in displaying and hiding the mobile menu and table of contents section on my website when viewed on a mobile device. I'm using vanilla JavaScript to add and remove classes, but it's taking about one second for the me ...

NextJS: Issue: Accessing a client module from a server component is not allowed. The imported name must be passed through instead

My current NextJS setup is structured as shown below: app/page.js 'use client'; import React from 'react'; export default function Home() { return (<div>Testing</div>); } app/layout.js export const metadata = { title ...

Using 'jquery.get' in combination with a servlet is

I need a servlet that can handle GET requests and return a specific string. A simple example of the code is shown below: public class QueryHandler extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) ...

Issue with Javascript variables

In Javascript, I have an array of strings that I need to use for loading images on my page through AJAX. After each image is loaded, there are additional tasks to be performed which include sending a HTTP request to delete the image. Below is the code I c ...

Unable to retrieve accurate Boolean data through ajax request

Imagine a scenario where we are working with the following Ajax request: $.ajax({ url:'myURL.php', data:{ ac:'do', isDoable:false } }); Now, on the backend, when processing the call data, the isDoable param ...

Capture a snapshot of a Bootstrap modal using JavaScript

var takeScreenShot = function(){ html2canvas(document.body, { onrendered: function(canvas) { var tempcanvas=document.createElement('canvas'); tempcanvas.width=1350; tempcanvas.height=1350; var context=tempcan ...

What is the method for transferring the value of a jQuery variable to a PHP variable without using AJAX?

Here is my JavaScript code: $('#affiliates_name').change(function(){ var id = $('#affiliates_name').val(); }); Below is the corresponding HTML: <select id="affiliates_name" style="display: none;" name="affiliates_name"> < ...

Alter the component and then refresh it

I am encountering an issue with a component that has an event handler for a "like" icon. The goal is to allow users to click the like icon, update the database to indicate their liking of the item, and then re-render the component to visually reflect this ...

Filtering the inner ng-repeat based on the variable of the outer ng-repeat

I have a collection of elements. Some of these elements are considered "children" of other elements known as "parent" elements. Instead of rearranging the JSON data received from the server, I am attempting to filter the results within the ng-repeat loop. ...

Interact with embedded elements in JavaScript by using the onClick event

Here is a JavaScript code snippet I've been working on: <div> <tr onClick="click1()"> <td> click 1 </td> <td onClick="click2()"> click 2 < ...

Enhance hover effects with JQuery through dynamic mouse movements

$(document).ready(function() { $(".hoverimage").hover( function(e) { updateCoords(this,e); openQuicktip(this); }, function() { closeQuicktip(); } ); $("area").hover( function(e) { updateCoords(this,e); openQuicktip(this); }, function ...

While attempting to add a member to a role, I encounter the following error: ReferenceError: mesage is not defined

Every time I work on the Discord bot code that assigns a role when activated, I encounter this error. I'm not sure if there's a hidden bug causing it, so if you spot it, please help me fix it! Error message. if(mesage.content.startsWith(prefix ...

What is the best way to activate Cropper once a file has been selected, without encountering a 404 error on the image?

I've been trying to integrate an image cropper into my website, but I'm encountering some issues that I can't seem to resolve. Expected outcome : Upon selecting a picture from the disk using the file input, a modal should appear prompting t ...

An error message stating "ReferenceError: str is not defined" was encountered in Firefox while using the Gettext Library

The gettext.js library seems to be giving me trouble. When I try to run the "index.html" file, an error message saying "ReferenceError: str is not defined" pops up. this.LCmessages[lang] = new jsGettext.Parse(str); I'm not sure where the str variabl ...