Extract the color of an individual character

There is a code snippet in JavaScript using p5.js that functions as a video filter:

    const density = '        .:░▒▓█'
//const density = '     .tiITesgESG'

  //let geist;
  let video
  let asciiDiv
  let playing = false
  let button

  function preload() {
  video = createVideo('assets/ripple.mp4', vidLoad)
}

function vidLoad() {
  video.loop()
    video.volume(0)
}

function setup() {
  noCanvas()

    //video = createCapture(VIDEO)
    //video = createVideo('assets/01.mp4');

  button = createButton('play');
  button.mousePressed(toggleVid);
  video.size(256, 160)
  //video.size(160, 160);
  asciiDiv = createDiv();
}

function toggleVid() {
  if (playing) {
    video.pause();
    button.html('play');
  } else {
    video.loop();
    button.html('pause');
  }
  playing = !playing;
}

function draw() {
  background(0);
  
  video.loadPixels();
  let asciiImage = '';

  //pixelarray
  for (let j = 0; j < video.height; j++) {
    for (let i = 0; i < video.width; i++) {
      const pixelIndex = (i+j*video.width) * 4;
      const r = video.pixels[pixelIndex + 0];
      const g = video.pixels[pixelIndex + 1];
      const b = video.pixels[pixelIndex + 2];
      const avg = (r + g + b) / 3;
      const len = density.length;
      const charIndex = floor(map(avg, 0, 255, len, 0));

      const c = density.charAt(charIndex);
      if (c == ' ') asciiImage += '&nbsp;'
  else asciiImage += c;
}
asciiImage += '<br/>'
  //console.log(row);
}
asciiDiv.html(asciiImage)
}

In addition, there is CSS code that appears like this:

 html, body {
 margin: 0;
 padding: 0;
 border: 10px solid black;
 
 background-color: #fff;
 /*
 //#fcbf45;
 //aaaaaa;
 */
 color: #000;
 //#ffd & #00b0aa;
 font-family: 'Courier Bold';
 line-height: 4pt;
 font-size: 5pt;
}

canvas {
 display: block; 
}

You can see the result here. I apologize for all the comments included.

Now, my inquiry revolves around whether it's feasible to alter the color of a specific character within the text. For instance, if I choose the rightmost darkest character from the 'density' constant, could I make just that character appear in blue?

Thank you for your help.

UPDATE: Following the advice provided below, I have implemented the following changes in the code:

const darkest = density[density.length-1]
  const c = density.charAt(charIndex)
  if (c == ' ') {
    asciiImage += '&nbsp;'
  
  } else {
    asciiImage += c;
  }
  if (c === darkest) {
    asciiImage += `<span class='blue'>${c}</span>`
  }

The updated result can be viewed here: https://i.stack.imgur.com/DiFeM.jpg. It seems the issue arises due to appending 'c' twice, correct?

Answer №1

Officially, no, you cannot directly alter the color of a specific character. However, you do have the option to enclose individual characters within an element (such as a span) that can be styled using CSS.

// identifies the darkest character in the sequence
const darkest = density[density.length - 1]
// if the current character matches the darkest character, wrap it in a span with the class 'blue.'
if(c === ' ') {
  asciiImage += '&nsbc;'
}
else if (c === darkest) {
  asciiImage += `<span class='blue'>${c}</span>`
}
else {
  asciiImage += c
}

To apply a blue color to these characters, adjust your CSS styling accordingly.

.blue {
  color: blue;
}

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

Access Sharepoint from an external site

Looking for assistance with a SharePoint list containing columns for Name, Position, Office, and Salary. Upon logging in with specific credentials to the SharePoint website, I need to retrieve all items from the list and showcase them on my own website. ...

Arranging cards in a stack using VueJS

I am currently working with a small vue snippet. Originally, I had v-for and v-if conditions in the snippet, but due to issues reading the array, it is now hardcoded. The current setup produces three cards stacked on top of each other. I am exploring opti ...

AngularJS - choosing the ng-model's index value

I'm looking to retrieve the selected item(s) from a select control along with their values or titles. Once the user has made their selections from the dropdown menu, I want to be able to determine the number of items selected and display their titles ...

Calculate the time difference in hours using time zone in Javascript

Within my JavaScript object, I have the following information: var dateobj = { date: "2020-12-21 03:31:06.000000", timezone: "Africa/Abidjan", timezone_type: 3 } var date = new Date(); var options = { timeZone: dateobj.timezone }; var curr_date ...

Guide on properly documenting custom function types in JSDoc or TypeScript to ensure accurate referencing for VSCode IntelliSense functionality

I am currently working on documenting custom function types within an object and would greatly appreciate any assistance: A Closer Look at the Issue Consider this basic object declaration with several function properties (addCoordinate, addCoordinateOne, ...

Javascript encountered an error upon attempting to return from the main function

I have a function that calls the database to perform an action: function callQuery(query) { db.query(query, (err, res) => { if (err) { // Error connecting to DB console.log(err.stack) } else { // Return the results ret ...

Navigating within two containers using the anchorScroll feature in AngularJS

I am trying to create a page with two columns of fixed height. The content in each column is generated using ng-repeat directive. Is it possible to implement scrolling within each column to a specific id using AngularJS? Code <div> Scroll to a p ...

Angular - Manipulating the selected option in a select box from the controller

My issue involves a select box that is defined in the following manner: <select ng-model="selectedSupplier" ng-options="supplier.name for supplier in suppliers"> </select> Within my controller, there is a button that doesn't have any r ...

Unable to navigate to partial view within MEAN application

I'm currently following a tutorial on creating single page applications using the MEAN stack. So far, I have successfully rendered the index.jade view. However, I encountered an issue when trying to route to a partial view as the DOM of the page does ...

Issue with Webpack - npm run start and build operation not functioning?

Although I typically use create-react-app for my React projects, I decided to create one without it. However, I am encountering issues with the webpack configuration as I am not very familiar with it: This is how my package.json file looks like: { " ...

Retrieving a result from a function call is a fundamental aspect of programming

I have a scenario where I am initiating a call from a controller within AngularJS. This call passes some data to a service in order to receive a response that needs to be conditionally checked. Controller patents.forEach(function(item){ // The "patents" ...

Isn't AJAX all about the same origin policy?

Despite my confusion surrounding the same domain origin policy and jQuery AJAX, I have noticed that when I make a GET request to a URL using jQuery, I am able to successfully retrieve the results. This goes against what I understood about the restriction ...

Display a div using Jquery depending on the visibility and checked value of another div

Trying to toggle the visibility of a div based on another div's input has proven to be quite challenging in this scenario. Here is the HTML setup: <div id="main-question"> <div class="form-group"> <div class="form-radios"> ...

JavaScript Loading Screen - Issues with window.onload functionality

I am currently working on creating a loading screen for my project. I need to use JavaScript to remove the CSS property "Display: none" from the page, but for some reason, my code is not functioning as expected. The Issue: I discovered that using window. ...

Retrieve data from multiple JSON tables using a JavaScript loop

Check out this Codepen for a working example. I am relatively new to Javascript, so I may not be approaching this problem the best way. If you have any suggestions on how I could improve my approach, I would greatly appreciate it; always looking to learn ...

Display hyperlinks upon hovering over text

In the sign-up form, there are options for two different types of users: teachers and students. When the sign-up option is selected, a drop-down menu with choices for teacher and student will appear. However, I would like it to function more like other w ...

What is the process of disabling console log in a Vue template?

Origins of the $log variable: Vue.prototype.$log = console.log Restricted Areas: <template> <!-- Restricted Area 1 --> <div @click="$log"> <!-- Restricted Area 2 --> {{ $log }} <!-- Restricted Area 3 -- ...

The functionality of Anchor `<a>` tags is compromised in Chrome when using the hashtag symbol (#)

Below is the code I have implemented on my website: <li><a href="/explore/#Sound">Sound</a></li> (This menu is visible on all pages) <a id="Sound"><a> (This is on the specific page where I want to link to) I have at ...

A custom class that uses toggleClass() does not trigger an alert upon a click event

I am encountering an issue with the toggleClass() function in jQuery that I haven't seen addressed before. Despite successfully toggling the class of one button when clicked, I am unable to trigger a click event on the newly toggled class. Here is th ...

Some browsers are failing to display the navigation bar on my website

After working on my website, www.alexanderpopov.org, I encountered an issue with the navigation bar disappearing on some computers and browsers. I'm using css to style it, but the problem persists. Below is the HTML code for your reference. Any advice ...