Friday, March 24, 2023
Learning Code
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
Learning Code
No Result
View All Result
Home JavaScript

Color Manipulation with JavaScript | HTML Goodies

learningcode_x1mckf by learningcode_x1mckf
September 28, 2022
in JavaScript
0
Color Manipulation with JavaScript | HTML Goodies
74
SHARES
1.2k
VIEWS
Share on FacebookShare on Twitter


CSS-in-JS Tutorials

One in every of many attracts of CSS libraries like Sass and Much less are their large assortment of coloration manipulation features resembling lighten, darken, saturate, and so on. With the rising recognition of CSS-in-JS, the necessity for JavaScript (JS) equivalents has adopted go well with. Proper on cue, a variety of JS libraries for coloration conversion and manipulation have cropped as much as make the roles of internet builders simpler. Actually, proper now it’s laborious to decide on which one to make use of. One library that comes advisable by the favored JSS CSS-in-JS library is solely referred to as “color“. It’s fairly characteristic wealthy, having extra to supply than say color2k and a smaller measurement than chroma.js. This internet growth tutorial will present an outline of a few of coloration’s many options and put them to work in an Angular Single Web page Software (SPA).

Earlier than getting began, it’s possible you’ll wish to take a look at our Introduction to CSS-in-JS tutorial.

How one can Setup and Set up the JSS coloration Library

The advisable option to set up coloration is to make use of the Node Package deal Supervisor (NPM). The command is solely:

$ npm set up coloration

And even npm i coloration if you’re actually into minimizing typing.

Then you may consult with it in your node.js information utilizing require:

const Shade = require('coloration');

In Angular, you must use import:

import Shade from 'coloration';

The uncovered Shade object supplies a couple of totally different constructors to select from, most of which settle for some permutation of Pink Inexperienced Blue (RGB) values. It is going to additionally settle for a restricted variety of strings, such because the oft-used HEX format:

const coloration = Shade('#FFFFFF');
const coloration = Shade('rgb(255, 255, 255)');
const coloration = Shade(r: 255, g: 255, b: 255);
const coloration = Shade.rgb(255, 255, 255);
const coloration = Shade.rgb([255, 255, 255]);

Below the covers, String constructors are dealt with by the color-string library.

You possibly can study extra about dynamic styling choices by studying our Dynamic Styling with JSS tutorial.

Exploring the JS Shade API

Shade’s API was closely impressed by color-js, whose manipulation features carefully resemble these of CSS instruments like Sass, LESS, and Stylus. However, earlier than we get to these, let’s have a look at methods to convert colours to different codecs.

CSS helps a large number of coloration sorts, from preset names like “aliceblue“, and “teal” to HEX (“#ee652e“), RGB (rgb(138, 238, 130)), and RGBA (rgba(0,255,0,0.75)).

Searching for the rgb quantity worth? Name the hex() technique:

coloration.hex() // #ffffff

Convert a coloration to an rgb object:

coloration.object(); // r: 255, g: 255, b: 255

Right here’s methods to set a hash of the colour worth and mirror the colour’s present mannequin:

coloration.rgb().array() // [255, 255, 255]

To get the person rgb values, use these:

coloration.crimson()   //255
coloration.inexperienced() //255
coloration.blue()  //255

Learn: Using an Angular Service to Read Sass Variables

Shade Manipulation Capabilities and CSS Colours

Sass comes with plenty of nice features that may simply be utilized to CSS colours. These features take a number of the sting out of selecting and manipulating colours. These embody darken and lighten, saturate and desaturate, rgba, and extra. So, too, with the coloration library. Right here’s a sampling:

//lighten by 50%
coloration.lighten(0.5)     // hsl(100, 50%, 50%) -> hsl(100, 50%, 75%)
//darken by 50%
coloration.darken(0.5)      // hsl(100, 50%, 50%) -> hsl(100, 50%, 25%)
coloration.saturate(0.5)    // hsl(100, 50%, 50%) -> hsl(100, 75%, 50%)
coloration.desaturate(0.5)  // hsl(100, 50%, 50%) -> hsl(100, 25%, 50%)
rgba(10, 10, 10, 0.8)

Different helpful manipulation features embody:

coloration.grayscale()      // #5CBF54 -> #969696
coloration.whiten(0.5)      // hwb(100, 50%, 50%) -> hwb(100, 75%, 50%)
coloration.blacken(0.5)     // hwb(100, 50%, 50%) -> hwb(100, 50%, 75%)

coloration.fade(0.5)        // rgba(10, 10, 10, 0.8) -> rgba(10, 10, 10, 0.4)
coloration.opaquer(0.5)     // rgba(10, 10, 10, 0.8) -> rgba(10, 10, 10, 1.0)

coloration.rotate(180)      // hsl(60, 20%, 20%) -> hsl(240, 20%, 20%)
coloration.rotate(-90)      // hsl(60, 20%, 20%) -> hsl(330, 20%, 20%)

coloration.combine(Shade("yellow"))        // cyan -> rgb(128, 255, 128)
coloration.combine(Shade("yellow"), 0.3)   // cyan -> rgb(77, 255, 179)

All the above features could also be chained collectively:

coloration.inexperienced(100).grayscale().lighten(0.6)

Different features present details about a coloration:

coloration.isLight()         // true
coloration.isDark()          // false

Utilizing coloration.js to Set Theme Colours

Within the final couple of articles on CSS-in-JS now we have been adapting the Using an Angular Service to Read Sass Variables Demo to make use of JSS to set an Angular part’s colours by way of @Enter parameters. Though JSS and coloration.js make an ideal pairing, every library can be utilized independently of the opposite. To emphasise that time, we are going to apply coloration.js to the Shade Service that defines the theme colours for the applying.

Within the app.part.scss file, Sass features are employed to set the mild and darkish variations of the bottom colours:

$backgroundColor: rgb(82, 172, 240);
$lightBackgroundCcolor: lighten($backgroundColor, 16%);
$hoverColor: blue;
$darkHoverColor: darken($hoverColor, 20%);
$focusBorderColor: darkgray;
$darkFocusBorderColor: darken($focusBorderColor, 40%);

Think about a state of affairs the place our utility was constructed utilizing vanilla CSS reasonably than Sass. With out entry to the Sass features, we might require one other technique of affecting the bottom colours. That might be a really perfect use of the colour library.

We might nonetheless have entry to the three base colours by way of CSS variables:

.color-demo-app 
  --background-color: rgb(82, 172, 240);
  --hover-color: blue;
  --focus-border-color: lightgray;


Now, in loadColors(), we are able to add two extra calls to the brand new setMapColor() operate for every CSS property’s mild and darkish variation:

import Shade from 'coloration';

const CSS_PREFIX = "--";
const CSS_SUFFIX = "coloration";
const CSS_DELIMITER = "-";

export enum PropertyNames 
  background  = 'background',
  hover="hover",
  focusborder="focus-border"


public loadColors() 
  // Learn the customized property of physique part with given title:
  const appElement = 
    doc.getElementsByClassName('color-demo-app');
  if (appElement && appElement.size > 0) 
    const appStyles = window.getComputedStyle(appElement[0]);
    Object.values(PropertyNames).forEach(propertyName => 
      const cssVariableName = CSS_PREFIX
        + `$propertyName$CSS_DELIMITER`
        + CSS_SUFFIX;
      const cssVariableValue = 
        appStyles.getPropertyValue(cssVariableName)
                  .exchange(' ', '');
      if (cssVariableValue) 
        this.setMapColor(propertyName, cssVariableValue);
      
      // load mild coloration 
      this.setMapColor(
        propertyName, 
        Shade(cssVariableValue).lighten(0.2).hex(),
        ColorOptions.mild
      );
      // load darkish coloration 
      this.setMapColor(
        propertyName, 
        Shade(cssVariableValue).darken(0.2).hex(),
        ColorOptions.darkish
      );
    );

    this.setThemeDefaults();
  


Extracting the code to set the _colorMap entry to a helper operate solely is sensible since now we have to do it thrice for every CSS property:

non-public setMapColor(
  propertyName: PropertyNames, 
  worth: string,
  colorOption = ColorOptions.commonplace 
) 
  const colorMapKey = <ColorProperty>
    title: propertyName,
    choice: colorOption
  ;
  this._colorMap.set(
    JSON.stringify(colorMapKey),
    worth
  );


You possibly can see how the entire above code works collectively within the stackblitz demo.

Conclusion

There are a couple of causes to like coloration libraries like coloration.js. Firstly, utilizing JavaScript to govern colours supplies extra scoping and dynamic execution to perform issues that may be fairly troublesome utilizing CSS, even with assist from extension libraries like Sass and Much less. One other enticing characteristic is their ease of use, at the very least the place coloration.js is anxious.

Learn extra CSS and web development tutorials by visiting our CSS programming section.



Source link

You might also like

Toolkit Allows JavaScript Devs to Program Embedded Devices – The New Stack

Select data value from grandparent div? – JavaScript – SitePoint

How to Handle Errors in JavaScript – Programming – MUO – MakeUseOf

Share30Tweet19
learningcode_x1mckf

learningcode_x1mckf

Recommended For You

Toolkit Allows JavaScript Devs to Program Embedded Devices – The New Stack

by learningcode_x1mckf
March 23, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Toolkit Allows JavaScript Devs to Program Embedded Devices  The New Stack Source link

Read more

Select data value from grandparent div? – JavaScript – SitePoint

by learningcode_x1mckf
March 23, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Select data value from grandparent div? - JavaScript  SitePoint Source link

Read more

How to Handle Errors in JavaScript – Programming – MUO – MakeUseOf

by learningcode_x1mckf
March 23, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

How to Handle Errors in JavaScript - Programming  MUO - MakeUseOf Source link

Read more

How to Use the Javascript Slice Method – hackernoon.com

by learningcode_x1mckf
March 23, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

How to Use the Javascript Slice Method  hackernoon.com Source link

Read more

Clean Code in JavaScript – SitePoint

by learningcode_x1mckf
March 23, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Clean Code in JavaScript  SitePoint Source link

Read more
Next Post
How to Automate Basic File Operations Using Java

How to Automate Basic File Operations Using Java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Related News

Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Eclipse Java downloads skyrocket – InfoWorld

March 14, 2023
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

The Once Popular Java Web Framework Comes Back to Life – Analytics India Magazine

February 21, 2023
Meta AI Open Sources Flashlight: Fast and Flexible Machine Learning Toolkit in C++

Meta AI Open Sources Flashlight: Fast and Flexible Machine Learning Toolkit in C++

September 13, 2022

Browse by Category

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

RECENT POSTS

  • Java Developer Survey Reveals Increased Need for Java … – PR Newswire
  • What You Should Definitely Pay Attention to When Hiring Java Developers – Modern Diplomacy
  • Java Web Frameworks Software Market Research Report 2023 … – Los Alamos Monitor

CATEGORIES

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

© 2022 Copyright Learning Code

No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#

© 2022 Copyright Learning Code

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?