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

Changing the color of a text box when it is disabled can be achieved through JavaScript

I'm facing an issue with the formatting of my HTML elements. Specifically, I have 2 combo boxes and one text box in which all 3 are disabled. However, when they are disabled, the background color of the text box does not match that of the combo boxes. ...

Generate listview items containing anchor tags automatically

I am currently developing a web application using Jquery Mobile. After retrieving data from a webservice function, I am utilizing an ajax call to display this data on my webpage. $('[data-role=page]').on('pageshow', function () { var u ...

Customizing Bootstrap Modal's backdrop CSS for a specific element

Upon opening a bootstrap modal, the background takes on a darker shade as seen here. I am looking to apply a CSS class that mimics this shading effect to a specific element. I prefer not to use any JavaScript for this task as it is purely about styling wi ...

Activating a function that requires locating a dynamically loaded element on the webpage using AJAX

I have a unique page on my website that allows users to make edits. Whenever they click on an item, the edit form is seamlessly loaded into a specialized section of the page using AJAX. Depending on the chosen item, the form fields are already prefilled w ...

Looking to transform an HTML table into a stylish CSS layout complete with a form submission button?

Recently, I've been delving into the world of CSS and PHP as I work on converting old code entirely into HTML and PHP with a touch of CSS. The visual aspect seems fine, but I've hit a roadblock with the submit form due to an IF statement in PHP. ...

Restrict page scrolling to the vertical position of a specified div [Using jQuery, javascript, and HTML]

Currently, I am in the process of developing a personal website that features numerous expandable items. My goal is to restrict the page scrolling to the height of the expanded item once it is opened. I do not want users to be able to scroll above or below ...

Creating an uncomplicated selector bar for a basic javascript slideshow

I've spent the last couple of hours teaching myself some basic JavaScript, so please bear with me. Currently, I have a simple code in place for a straightforward slideshow on a website. Here is the JavaScript I'm using (where the 'slide&apo ...

Automatically clear out table rows once the maximum row limit is reached, then append new data using the WebSocket data in JavaScript

Recently, I delved into JavaScript and faced a dilemma with my Bitcoin Price update dashboard. The data is streaming in through an external WebSocket, updating the prices every second. But here's the catch - the table rows are going crazy! To maintain ...

Achieving optimal performance with scoped CSS in Vue.js

As I work on creating a new app using VueJs, I have noticed the implementation of "css scoped" as shown below: <style scoped> .example { color: red; } </style> <template> <div class="example">hi</div> </template> ...

How To Access a View by Clicking in Ionic Framework

I have designed the main screen shown below. When each link is clicked, it should open the corresponding view. https://i.sstatic.net/H84jt.png Here is what I have created so far: Main Screen <body ng-app="starter"> <ion-pane> < ...

Issue with AngularJS expression not functioning as expected in Chrome for setting input type to "file"

I have encountered a strange bug while working on an Angular form builder application. The issue arises in Chrome when I try to dynamically set the input type based on a variable. Surprisingly, this method works perfectly for all input types except "file", ...

How come Font Awesome icons aren't appearing in my link?

Is my question strange? I've noticed a peculiar behavior when using fontawesome. Normally, it displays correctly, and I have already referred to the documentation, but none of the solutions I found here seem to solve my issue. Sources I have tried: ...

Is there a way to send a non-JSON value to an angular.js http.post function?

Struggling to send two parameters using the HTTP POST method in Angular.js. Here is the code I have implemented: Controller var installerApp = angular.module('installerApp', []); installerApp.controller('InstallerCntlr',function($scop ...

Error message: When accessing react-native camera roll, the message "this.state.photos is not a valid object" appears

Encountering an error while attempting to implement camera roll functionality in my demo app. The error states, "null is not an object (evaluating 'this.state.photos')" View iOS Error Message. I am a beginner developer working on my first react-n ...

Is it possible for data transmitted or received through a socket written in various languages to be comprehended by both parties involved?

Is it possible for data to be transmitted accurately between two programs written in different languages (C++ and JavaScript using Node.js in this case) when connected through a socket? ...

Tips for invoking C language code from JavaScript by using the js-ctypes extension in Firefox

I need assistance with developing a Firefox extension that requires calling native C code. Here is my C program code: #include<windows.h> int add(int a, int b) { return(a + b); } And here is my JavaScript code: var {Cu} = require('chrome ...

"Searching for the index of a clicked element? Here's how to do

I am trying to determine the index of a clicked anchor element in my navigation using jQuery. However, when I use the following code snippet, I always get zero in the console: $('.navigation ul li a').click(function(e) { e.preventDefault(); ...

Searching Firebase by using comparison operators on various fields

const FindFiis = async () => { const data: any[] = []; // Firebase query with inequalities on different fields to retrieve docs. // Objective: Select documents where dividendYield is between 8 and 20 and pvp is less than or equal to 1. ...

Updating/Timer feature for a single feed out of two -- Combining data with $q.all()

I'm revisiting a question I previously asked here. The approach I took involved using the $q.all() method to resolve multiple http calls and then filtering and merging the data. Everything was working fine, but now I want to refresh one of the feeds ...

The issue with the max-height transition not functioning properly arises when there are dynamic changes to the max-height

document.querySelectorAll('.sidebarCategory').forEach(el =>{ el.addEventListener('click', e =>{ let sub = el.nextElementSibling if(sub.style.maxHeight){ el.classList.remove('opened&apos ...