Tweening Colors on Spark AR via Script - instagram

what would be the equivalent of a transition Patch in Reactive script? I would like to tween a color from say 0,0,0,1 to 1,1,1,1 in RGBA. I know ho to animate a single value as alpha, like this:
const timeDriver = Animation.timeDriver(timeDriverParameters);
const alphaSampler = Animation.samplers.linear(1, 0);
const alphaAnimation = Animation.animate(timeDriver, alphaSampler);
mymaterial.opacity = alphaAnimation;
Using visual patches you can use a Transform Patch to link a Vector3 to an animation progress. I cannot find something like this anywhere in the docs for reactive script. anyone can tell me?
Thank you!

you need to look at ShaderModule. Find the material by name, and then you can use setTexture.
const R = require('Reactive');
const A = require('Animation');
const S = require('Shaders');
const Materials = require('Materials');
const material = Materials.get('matName');
const driver = A.timeDriver({ durationMilliseconds : 1000});
const sampler = A.samplers.linear(
[1, 1, 1, 1],
[0, 0, 0, 1]
);
const colorAnimation = A.animate(
driver,
sampler
);
material.setTexture(
R.pack4(
colorAnimation.get(0),
colorAnimation.get(1),
colorAnimation.get(2),
colorAnimation.get(3)
),
{textureSlotName: S.DefaultMaterialTextures.DIFFUSE}
);
Here i've used ArrayOfScalarSamplers, but it's not crucial.

Related

Create a grid on top of an image

I hope you are all well and safe.
In NodeJS, I wanted to create a grid on top of an image. Like this:
Image without grid
Image with grid
Can someone tell me, please, how can I achieve this (some library or something)?
After creating the grid, I would like to go square by square and check the information for each square. Does anyone have any ideas?
Thank you very much for your time!
The first answer has a native Cairo dependency... Below I used pureimage instead, which has Pure JS implementations of jpeg and png encoding.
static drawParallel = (canvas, step, isYAxis) => {
const c2d = canvas.getContext('2d')
const numberOfSteps = (canvas.width / step) | 0
const end = isYAxis ? canvas.height : canvas.width
console.log(`Steps: ${numberOfSteps}\n`)
c2d.lineWidth = 1.1 // PureImage hides thin lines
c2d.strokeStyle = 'rgba(255,192,203,0.69)'
for (let i = 1; i < numberOfSteps; i++) {
const from = i * step
const to = i * step
const mx = isYAxis ? [from, 0, to, end] : [0, from, end, to]
console.log(`Stroking ${mx[0]}, ${mx[1]} to ${mx[2]}, ${mx[3]}`)
c2d.beginPath()
c2d.moveTo(mx[0], mx[1])
c2d.lineTo(mx[2], mx[3])
c2d.stroke()
}
}
source: https://stackblitz.com/edit/feathersjs-7kqlyt
I would use Canvas. You can use it for all sorts of image jobs and editing. For example, you could get a transparent PNG image of the grid and lay it on:
const Canvas = require("canvas");
const canvas = Canvas.createCanvas(619, 319);
const ctx = canvas.getContext("2d");
let img = await Canvas.loadImage("./path/to/image.png");
ctx.drawImage(img, 0, 0, img.width, img.height);
let grid = await Canvas.loadImage("./path/to/grid.png");
ctx.drawImage(grid, 0, 0, canvas.width, canvas.height);
console.log(canvas.toDataURL());
I myself managed to get something like this.

Pixi.js v5 - apply alpha to displacement map

I'm scaling a displacement map on click but would like that map to fade away once it reaches almost full scale. The idea is that the filter should be non-existent after a couple of seconds.
const app = new PIXI.Application({
view: document.querySelector("#canvas"),
width: 512,
height: 512
});
const logo = PIXI.Sprite.fromImage("https://unsplash.it/600");
const displacement = PIXI.Sprite.fromImage("https://images.unsplash.com/photo-1541701494587-cb58502866ab?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80");
const filter = new PIXI.filters.DisplacementFilter(displacement);
logo.anchor.set(0.5);
logo.position.set(256);
logo.interactive = true;
displacement.anchor.set(0.5);
displacement.position.set(256);
displacement.scale.set(0.05)
displacement.alpha = 1
app.stage.filterArea = app.screen;
app.stage.filters = [filter];
app.stage.addChild(logo, displacement);
app.ticker.add(function() {
displacement.scale.x += 0.05
displacement.scale.y += 0.05
if (displacement.scale.x > 10) app.ticker.stop()
});
logo.on('mousedown', function() {
displacement.scale.set(0.05)
app.ticker.start()
});
Here's what I have so far:
https://codepen.io/mariojankovic/pen/pojjNae?editors=0111
I've only just started looking at Pixi but I think you want to use the scale property of the displacement filter. This value says how far to shift. Reducing this value to 0 will lessen its effect to none.
https://pixijs.download/dev/docs/PIXI.filters.DisplacementFilter.html
https://pixijs.download/dev/docs/PIXI.filters.DisplacementFilter.html#scale
The way it works is it uses the values of the displacement map to look
up the correct pixels to output. This means it's not technically
moving the original. Instead, it's starting at the output and asking
"which pixel from the original goes here". For example, if a
displacement map pixel has red = 1 and the filter scale is 20, this
filter will output the pixel approximately 20 pixels to the right of
the original.
https://codepen.io/PAEz/pen/BaoREwv
const app = new PIXI.Application({
view: document.querySelector("#canvas"),
width: 512,
height: 512
});
const logo = PIXI.Sprite.fromImage("https://unsplash.it/600");
const displacement = PIXI.Sprite.fromImage(
"https://images.unsplash.com/photo-1541701494587-cb58502866ab?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80"
);
const filter = new PIXI.filters.DisplacementFilter(displacement);
logo.anchor.set(0.5);
logo.position.set(256);
logo.interactive = true;
displacement.anchor.set(0.5);
displacement.position.set(256);
displacement.scale.set(0.0);
displacement.alpha = 1;
app.stage.filterArea = app.screen;
app.stage.filters = [filter];
app.stage.addChild(logo, displacement);
const displacementScaleFrom = 0.05;
const displacementScaleTo = 10 ;
const displacementStep = 0.05;
const filterScaleFrom = 20;// the default value for the filter is 20
const filterStep = filterScaleFrom / ((displacementScaleTo-displacementScaleFrom) / displacementStep);
app.ticker.add(function () {
displacement.scale.x += displacementStep;
displacement.scale.y += displacementStep;
filter.scale.x -= filterStep;
filter.scale.y -= filterStep;
if (displacement.scale.x >= displacementScaleTo) {
app.ticker.stop();
filter.scale.x = 0;
filter.scale.y = 0;
}
});
logo.on("mousedown", function () {
displacement.scale.set(displacementScaleFrom);
filter.scale.x = filterScaleFrom;
filter.scale.y = filterScaleFrom;
app.ticker.start();
});

What to use as inputs in OpenCV calibrateCamera cameraMatrix and distCoeffs parameters?

I'm trying to get calibrateCamera working on my Node.js backend. The library is working fine, but I'm having trouble with the OpenCV functions not giving any error messages if I have faulty inputs. I'm kind of flying in the dark.
But that's beside the point. I've taken 17 images of the chessboard calibration pattern, and got the code to detect the pattern in all of the images. Everything works just fine until I call cv.calibrateCamera(), probably due to me not knowing what I should use as the required inputs for cameraMatrix and distCoeff (4th and 5th input parameters). However, I can't be 100% this is the issue because of not receiving any error messages from errors in the cv... functions.
I tried to follow the example at https://docs.opencv.org/3.1.0/dc/dbb/tutorial_py_calibration.html , but on python in the tutorial you can use None as inputs to cameraMatrix and distCoeff. I tried to use null, but that didn't work either.
Any help would be appreciated.
const size = new cv.Size(9,6);
let mat = null;
let objpt = [];
for(let i=0;i<9;i++) {
for(let j=0;j<6;j++) {
objpt.push(cv.Point(2.5*i,2.5*j,0))
}
}
let objectPoints = [];
let imagePoints =[];
for (let i=0; i < 17;i++) {
mat = cv.imread('./calib/calib'+(i+1)+'.jpg');
let smallmat = mat.resize(756,1008);
const corners = smallmat.findChessboardCorners(size);
if (corners.returnValue) {
objectPoints = objectPoints.concat(objpt);
imagePoints = imagePoints.concat(corners.corners);
}
}
// THIS IS WHERE EXECUTION JUST STOPS WITH NO ERROR MESSAGE
cv.calibrateCamera(
objectPoints,
imagePoints,
new cv.Size(756,1008),
new cv.Mat(3, 3, cv.CV_32FC1,0),
[0,0,0,0,0]
);
According to the test parameters should be passed like this:
[_objectPoints, _objectPoints],
[imagePoints, imagePoints],
imageSize,
_cameraMatrix,
distCoefficients
where
const _cameraMatrix = new cv.Mat([
[800, 0, 100],
[0, 800, 100],
[0, 0, 1]
], cv.CV_64F);
and
const distCoefficients = [0, 0.5, 1.0, 1.0];

How and when to use PIXI.RenderTexture

I am building a tool which visualises bicycle wheels. It uses approximately 100 PIXI.Graphics to build the entire wheel, which is all placed in a PIXI.Container and then rendered. It seems like quite a lot to render every frame, so I was looking into the PIXI.RenderTexture class and thought it might make sense to use it in this case. So question 1, is this a good use case? and question 2, how can I use it because I am having trouble working it out.
const options = {
transparent: true,
antialias: true,
backgroundColor: 0xffffff,
resolution: window.devicePixelRatio,
view: canvasEle,
};
const app = new PIXI.Application(width, height, options);
const wrapper = new PIXI.Container(); // Wrapper is used for zooming and panning the wheel
app.stage.addChild(wrapper);
const wheel = new Wheel(wheelOpts); // Returns PIXI.Container full of PIXI.Graphics
wrapper.addChild(wheel);
And my attempt to use the renderTexture is as follows. But I can't seem to work it out
const options = {
transparent: true,
antialias: true,
backgroundColor: 0xffffff,
resolution: window.devicePixelRatio,
view: canvasEle,
};
const app = new PIXI.Application(width, height, options);
const wrapper = new PIXI.Container(); // Wrapper is used for zooming and panning the wheel
app.stage.addChild(wrapper);
const wheelRenderTexture = new PIXI.RenderTexture.create(width, height);
const wheelSprite = new PIXI.Sprite(wheelRenderTexture)
wrapper.addChild(wheelSprite)
const wheel = new Wheel(wheelOpts); // Returns PIXI.Container full of PIXI.Graphics
app.ticker.add(() =>
{
app.renderer.render(wheel, wheelRenderTexture);
})
Thanks for any help
I worked out how to use it and made a small jsfiddle https://jsfiddle.net/hp98ygz5/1/
const width = 600
const height = 600
var app = new PIXI.Application(width, height, {backgroundColor : 0xffffff});
document.body.appendChild(app.view);
const wheelRenderTexture = PIXI.RenderTexture.create(width, height);
const wheelRenderSprite = new PIXI.Sprite(wheelRenderTexture);
app.stage.addChild(wheelRenderSprite)
const wheelContainer = new PIXI.Container()
//app.stage.addChild(wheelContainer)
wheelContainer.addChild(drawCircle(100,100,50,0xfec3dc,2,0Xfe68a4))
wheelContainer.addChild(drawCircle(100,100,20,0xFFCC66,2,0X55ff77))
app.renderer.render(wheelContainer,wheelRenderTexture)
I am not sure what was wrong with the above example but it works now

How to change node.js's console font color?

I had to change the console background color to white because of eye problems, but the font is gray colored and it makes the messages unreadable. How can I change it?
Below you can find colors reference of text to command when running node.js application:
console.log('\x1b[36m%s\x1b[0m', 'I am cyan'); //cyan
console.log('\x1b[33m%s\x1b[0m', stringToMakeYellow); //yellow
Note %s is where in the string (the second argument) gets injected. \x1b[0m resets the terminal color so it doesn't continue to be the chosen color anymore after this point.
Colors reference
Reset = "\x1b[0m"
Bright = "\x1b[1m"
Dim = "\x1b[2m"
Underscore = "\x1b[4m"
Blink = "\x1b[5m"
Reverse = "\x1b[7m"
Hidden = "\x1b[8m"
FgBlack = "\x1b[30m"
FgRed = "\x1b[31m"
FgGreen = "\x1b[32m"
FgYellow = "\x1b[33m"
FgBlue = "\x1b[34m"
FgMagenta = "\x1b[35m"
FgCyan = "\x1b[36m"
FgWhite = "\x1b[37m"
FgGray = "\x1b[90m"
BgBlack = "\x1b[40m"
BgRed = "\x1b[41m"
BgGreen = "\x1b[42m"
BgYellow = "\x1b[43m"
BgBlue = "\x1b[44m"
BgMagenta = "\x1b[45m"
BgCyan = "\x1b[46m"
BgWhite = "\x1b[47m"
BgGray = "\x1b[100m"
EDIT:
For example, \x1b[31m is an escape sequence that will be intercepted by your terminal and instructs it to switch to the red color. In fact, \x1b is the code for the non-printable control character escape. Escape sequences dealing only with colors and styles are also known as ANSI escape code and are standardized, so therefore they (should) work on any platform.
Wikipedia has a nice comparison of how different terminals display colors
https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
There are multiple packages available for formatting console text in Node.js. The most popular are:
chalk —
cli-color —
colors — > EDIT: colors no longer recommended as it has denial of service vulnerability
see: https://snyk.io/blog/open-source-npm-packages-colors-faker/ for details
Usage:
CHALK:
const chalk = require('chalk');
console.log(chalk.red('Text in red'));
CLI-COLOR:
const clc = require('cli-color');
console.log(clc.red('Text in red'));
If you want to change the colors directly yourself without a module try
console.log('\x1b[36m', 'sometext' ,'\x1b[0m');
First \x1b[36m to change the colors to 36 and then back to terminal color 0.
Here's a list of ANSI color codes
This is a list of available colours (both background and foreground) in the console with some available actions (like reset, reverse, etc).
const colours = {
reset: "\x1b[0m",
bright: "\x1b[1m",
dim: "\x1b[2m",
underscore: "\x1b[4m",
blink: "\x1b[5m",
reverse: "\x1b[7m",
hidden: "\x1b[8m",
fg: {
black: "\x1b[30m",
red: "\x1b[31m",
green: "\x1b[32m",
yellow: "\x1b[33m",
blue: "\x1b[34m",
magenta: "\x1b[35m",
cyan: "\x1b[36m",
white: "\x1b[37m",
gray: "\x1b[90m",
crimson: "\x1b[38m" // Scarlet
},
bg: {
black: "\x1b[40m",
red: "\x1b[41m",
green: "\x1b[42m",
yellow: "\x1b[43m",
blue: "\x1b[44m",
magenta: "\x1b[45m",
cyan: "\x1b[46m",
white: "\x1b[47m",
gray: "\x1b[100m",
crimson: "\x1b[48m"
}
};
Here's an example of how to use it:
console.log(colours.bg.blue, colours.fg.white, "I am a white message with a blue background", colours.reset) ;
// Make sure that you don't forget "colours.reset" at the so that you can reset the console back to it's original colours.
Or you can install some utility modules:
npm install console-info console-warn console-error --save-dev
These modules will show something like the following to the console when you use them:
to color your output You can use examples from there:
https://help.ubuntu.com/community/CustomizingBashPrompt
Also a Gist for nodeJs
For example if you want part of the text in red color, just do console.log with:
"\033[31m this will be red \033[91m and this will be normal"
Based on that I've created "colog" extension for Node.js. You can install it using:
npm install colog
Repo and npm:
https://github.com/dariuszp/colog
Emoji
You can use colors for text as others mentioned in their answers.
But you can use emojis instead! for example, you can use⚠️ for warning messages and 🛑 for error messages.
Or simply use these notebooks as a color:
📕: error message
📙: warning message
📗: ok status message
📘: action message
📓: canceled status message
📔: Or anything you like and want to recognize immediately by color
🎁 Bonus:
This method also helps you to quickly scan and find logs directly in the source code.
for example:
console.log('Bring with ❤️ to you from Mojtaba Hosseini');
Some Linux distributions default emoji font may not be colorful by default and you may want to make them colorful, first.
How to open emoji picker?
mac os: control + command + space
windows: win + .
linux: control + . or control + ;
Reset: "\x1b[0m"
Bright: "\x1b[1m"
Dim: "\x1b[2m"
Underscore: "\x1b[4m"
Blink: "\x1b[5m"
Reverse: "\x1b[7m"
Hidden: "\x1b[8m"
FgBlack: "\x1b[30m"
FgRed: "\x1b[31m"
FgGreen: "\x1b[32m"
FgYellow: "\x1b[33m"
FgBlue: "\x1b[34m"
FgMagenta: "\x1b[35m"
FgCyan: "\x1b[36m"
FgWhite: "\x1b[37m"
FgGray: "\x1b[90m"
BgBlack: "\x1b[40m"
BgRed: "\x1b[41m"
BgGreen: "\x1b[42m"
BgYellow: "\x1b[43m"
BgBlue: "\x1b[44m"
BgMagenta: "\x1b[45m"
BgCyan: "\x1b[46m"
BgWhite: "\x1b[47m"
FgGray: "\x1b[100m"
For example if you want to have a Dim, Red text with Blue background you can do it in Javascript like this:
console.log("\x1b[2m", "\x1b[31m", "\x1b[44m", "Sample Text", "\x1b[0m");
The order of the colors and effects seems to not be that important but always remember to reset the colors and effects at the end.
Per this documentation, you can change the colors based on the data type of the output:
// you'll need the util module
var util = require('util');
// let's look at the defaults:
util.inspect.styles
{ special: 'cyan',
number: 'yellow',
boolean: 'yellow',
undefined: 'grey',
null: 'bold',
string: 'green',
date: 'magenta',
regexp: 'red' }
// what are the predefined colors?
util.inspect.colors
{ bold: [ 1, 22 ],
italic: [ 3, 23 ],
underline: [ 4, 24 ],
inverse: [ 7, 27 ],
white: [ 37, 39 ],
grey: [ 90, 39 ],
black: [ 30, 39 ],
blue: [ 34, 39 ],
cyan: [ 36, 39 ],
green: [ 32, 39 ],
magenta: [ 35, 39 ],
red: [ 31, 39 ],
yellow: [ 33, 39 ] }
These appear to be ANSI SGR escape codes, where the first number is the code to emit before the output, and the second number is the code to emit after. So if we look at the chart of ANSI SGR codes on Wikipedia, you'll see that most of these start with a number 30-37 to set the foreground color, and end in 39 to reset to the default foreground color.
So one thing I don't like is how dark some of these are. Especially dates. Go ahead and try new Date() in the console. Dark magenta on black is really hard to read. Let's change that to a light magenta instead.
// first define a new color
util.inspect.colors.lightmagenta = [95,39];
// now assign it to the output for date types
util.inspect.styles.date = 'lightmagenta';
Now when you try new Date(), the output is much more readable.
If you'd like to set colors automatically when launching node, create a script that launches the repl, like this:
// set your colors however desired
var util = require('util');
util.inspect.colors.lightmagenta = [95,39];
util.inspect.styles.date = 'lightmagenta';
// start the repl
require('repl').start({});
Save this file (for example, init.js), then run node.exe init.js. It will set the colors and launch the node.js command prompt.
(Thanks to loganfsmyth in this answer for the repl idea.)
I found this answer above (https://stackoverflow.com/a/41407246/4808079) very useful, but incomplete. If you only ever wanted to color something once, I guess it'd be fine, but I think sharing it in a runnable functional form is much more applicable to real life use cases.
const Color = {
Reset: "\x1b[0m",
Bright: "\x1b[1m",
Dim: "\x1b[2m",
Underscore: "\x1b[4m",
Blink: "\x1b[5m",
Reverse: "\x1b[7m",
Hidden: "\x1b[8m",
FgBlack: "\x1b[30m",
FgRed: "\x1b[31m",
FgGreen: "\x1b[32m",
FgYellow: "\x1b[33m",
FgBlue: "\x1b[34m",
FgMagenta: "\x1b[35m",
FgCyan: "\x1b[36m",
FgWhite: "\x1b[37m",
FgGray: "\x1b[90m",
BgBlack: "\x1b[40m",
BgRed: "\x1b[41m",
BgGreen: "\x1b[42m",
BgYellow: "\x1b[43m",
BgBlue: "\x1b[44m",
BgMagenta: "\x1b[45m",
BgCyan: "\x1b[46m",
BgWhite: "\x1b[47m"
BgGray: "\x1b[100m",
}
function colorString(color, string) {
return `${color}${string}${Color.Reset}`;
}
function colorLog(color, ...args) {
console.log(...args.map(
(it) => typeof it === "string" ? colorString(color, string) : it
));
}
Use it like this:
colorLog(Color.FgYellow, "Some Yellow text to console log", { someObj: true });
console.log([
colorString(Color.FgRed, "red"),
colorString(Color.FgGreen, "green"),
colorString(Color.FgBlue, "blue"),
].join(", "));
A handy one-liner I wrote for npm scripts that can't have dependencies:
const { r, g, b, w, c, m, y, k } = [
['r', 1], ['g', 2], ['b', 4], ['w', 7],
['c', 6], ['m', 5], ['y', 3], ['k', 0],
].reduce((cols, col) => ({
...cols, [col[0]]: f => `\x1b[3${col[1]}m${f}\x1b[0m`
}), {})
console.log(`${g('I')} love ${r('Italy')}`)
r,g,b,w,c,m,y,k stands for red, green, blue, white, cyan, magenta, yellow and black.
If you want to keep it SIMPLE without using any external module / learn new APIs / hacking the core console functions:
const LCERROR = '\x1b[31m%s\x1b[0m'; //red
const LCWARN = '\x1b[33m%s\x1b[0m'; //yellow
const LCINFO = '\x1b[36m%s\x1b[0m'; //cyan
const LCSUCCESS = '\x1b[32m%s\x1b[0m'; //green
const logger = class {
static error(message, ...optionalParams) { console.error(LCERROR, message, ...optionalParams) }
static warn(message, ...optionalParams) { console.warn(LCWARN, message, ...optionalParams) }
static info(message, ...optionalParams) { console.info(LCINFO, message, ...optionalParams) }
static success(message, ...optionalParams) { console.info(LCSUCCESS, message, ...optionalParams) }
}
// then instead (as presented in the accepted answer)
// console.error(LCERROR, 'Error message in red.');
// you write:
logger.error('Error message in red.');
// or with multiple parameters (only the message will be red):
logger.error('Error message in red.', 1, false, null, {someKey: 'whatever'});
// or use backticks (template literal) instead multiple params:
logger.error(`This will be red as ${foo} and ${bar} too.`);
Now you can use your logger in the same way as you would with console. There's no new API to remember... Normally you would put it into a module (logger.js) and export the class to be able to use it everywhere in your app as const logger = require('./logger');
This library by Sindre Sorhus is the best at the moment:
chalk
Highly performant
Doesn't extend String.prototype
Expressive API
Ability to nest styles
Clean and focused
Auto-detects color support
Actively maintained
Used by 5500+ modules
No libraries no complications just simple:
console.log(red('Error!'));
function red(s) {
return '\033[31m' + s;
}
For a popular alternative to colors that doesn't mess with the built-in methods of the String object, I recommend checking out cli-color.
Includes both colors and chainable styles such as bold, italic, and underline.
For a comparison of various modules in this category, see here.
I overloaded the console methods.
var colors={
Reset: "\x1b[0m",
Red: "\x1b[31m",
Green: "\x1b[32m",
Yellow: "\x1b[33m"
};
var infoLog = console.info;
var logLog = console.log;
var errorLog = console.error;
var warnLog = console.warn;
console.info= function(args)
{
var copyArgs = Array.prototype.slice.call(arguments);
copyArgs.unshift(colors.Green);
copyArgs.push(colors.Reset);
infoLog.apply(null,copyArgs);
};
console.warn= function(args)
{
var copyArgs = Array.prototype.slice.call(arguments);
copyArgs.unshift(colors.Yellow);
copyArgs.push(colors.Reset);
warnLog.apply(null,copyArgs);
};
console.error= function(args)
{
var copyArgs = Array.prototype.slice.call(arguments);
copyArgs.unshift(colors.Red);
copyArgs.push(colors.Reset);
errorLog.apply(null,copyArgs);
};
// examples
console.info("Numeros",1,2,3);
console.warn("pares",2,4,6);
console.error("reiniciandooo");
The output is.
Came across this question, and wanted to use some colors on stdout without any dependencies. This combines some of the other great answers here.
Here's what I've got. (Requires node v4 or greater)
// colors.js
const util = require('util')
function colorize (color, text) {
const codes = util.inspect.colors[color]
return `\x1b[${codes[0]}m${text}\x1b[${codes[1]}m`
}
function colors () {
let returnValue = {}
Object.keys(util.inspect.colors).forEach((color) => {
returnValue[color] = (text) => colorize(color, text)
})
return returnValue
}
module.exports = colors()
Just require the file, then use it like so:
const colors = require('./colors')
console.log(colors.green("I'm green!"))
The predefinied color codes are available here
There are two ways to look at changing colors for a Node.js console today.
One is through general-purpose libraries that can decorate a text string with color tags, which you then output through the standard console.log.
The top libraries for that today:
chalk
colors
cli-color
And the other way - patching the existing console methods. One such library - manakin lets you automatically set standard colors for all your console methods (log, warn, error and info).
One significant difference from the generic color libraries - it can set colors either globally or locally, while keeping consistent syntax and output format for every Node.js console method, which you then use without having to specify the colors, as they are all set automatically.
I had to change the console background color to white because of eye problems, but the font is gray colored and it makes the messages unreadable. How can I change it?
Specifically for your problem, here's the simplest solution:
var con = require('manakin').global;
con.log.color = 30; // Use black color for console.log
It will set black color for every console.log call in your application. See more color codes.
Default colors as used by manakin:
paint-console
Simple colorable log. Support inspect objects and single line update
This package just repaint console.
install
npm install paint-console
usage
require('paint-console');
console.info('console.info();');
console.warn('console.warn();');
console.error('console.error();');
console.log('console.log();');
demo
This somewhat depends on what platform you are on. The most common way
to do this is by printing ANSI escape sequences. For a simple example,
here's some python code from the blender build scripts:
// This is a object for use ANSI escape to color the text in the terminal
const bColors = {
HEADER : '\033[95m',
OKBLUE : '\033[94m',
OKGREEN : '\033[92m',
WARNING : '\033[93m',
FAIL : '\033[91m',
ENDC : '\033[0m',
BOLD : '\033[1m',
UNDERLINE : '\033[4m'
}
To use code like this, you can do something like
console.log(`${bColors.WARNING} My name is sami ${bColors.ENDC}`)
I don't want any dependency for this and only these worked for me on OS X. All other samples from answers here gave me Octal literal errors.
Reset = "\x1b[0m"
Bright = "\x1b[1m"
Dim = "\x1b[2m"
Underscore = "\x1b[4m"
Blink = "\x1b[5m"
Reverse = "\x1b[7m"
Hidden = "\x1b[8m"
FgBlack = "\x1b[30m"
FgRed = "\x1b[31m"
FgGreen = "\x1b[32m"
FgYellow = "\x1b[33m"
FgBlue = "\x1b[34m"
FgMagenta = "\x1b[35m"
FgCyan = "\x1b[36m"
FgWhite = "\x1b[37m"
FgGray = "\x1b[90m"
BgBlack = "\x1b[40m"
BgRed = "\x1b[41m"
BgGreen = "\x1b[42m"
BgYellow = "\x1b[43m"
BgBlue = "\x1b[44m"
BgMagenta = "\x1b[45m"
BgCyan = "\x1b[46m"
BgWhite = "\x1b[47m"
BgGray = "\x1b[100m"
source: https://coderwall.com/p/yphywg/printing-colorful-text-in-terminal-when-run-node-js-script
var colorSet = {
Reset: "\x1b[0m",
Red: "\x1b[31m",
Green: "\x1b[32m",
Yellow: "\x1b[33m",
Blue: "\x1b[34m",
Magenta: "\x1b[35m"
};
var funcNames = ["info", "log", "warn", "error"];
var colors = [colorSet.Green, colorSet.Blue, colorSet.Yellow, colorSet.Red];
for (var i = 0; i < funcNames.length; i++) {
let funcName = funcNames[i];
let color = colors[i];
let oldFunc = console[funcName];
console[funcName] = function () {
var args = Array.prototype.slice.call(arguments);
if (args.length) {
args = [color + args[0]].concat(args.slice(1), colorSet.Reset);
}
oldFunc.apply(null, args);
};
}
// Test:
console.info("Info is green.");
console.log("Log is blue.");
console.warn("Warn is orange.");
console.error("Error is red.");
console.info("--------------------");
console.info("Formatting works as well. The number = %d", 123);
logger/index.js
const colors = {
Reset : "\x1b[0m",
Bright : "\x1b[1m",
Dim : "\x1b[2m",
Underscore : "\x1b[4m",
Blink : "\x1b[5m",
Reverse : "\x1b[7m",
Hidden : "\x1b[8m",
FgBlack : "\x1b[30m",
FgRed : "\x1b[31m",
FgGreen : "\x1b[32m",
FgYellow : "\x1b[33m",
FgBlue : "\x1b[34m",
FgMagenta : "\x1b[35m",
FgCyan : "\x1b[36m",
FgWhite : "\x1b[37m",
BgBlack : "\x1b[40m",
BgRed : "\x1b[41m",
BgGreen : "\x1b[42m",
BgYellow : "\x1b[43m",
BgBlue : "\x1b[44m",
BgMagenta : "\x1b[45m",
BgCyan : "\x1b[46m",
BgWhite : "\x1b[47m",
};
module.exports = () => {
Object.keys(colors).forEach(key => {
console['log' + key] = (strg) => {
if(typeof strg === 'object') strg = JSON.stringify(strg, null, 4);
return console.log(colors[key]+strg+'\x1b[0m');
}
});
}
app.js
require('./logger')();
Then use it like:
console.logBgGreen(" grüner Hintergrund ")
Coolors
It's pretty good for use or extend. You can use simply:
var coolors = require('coolors');
console.log(coolors('My cool console log', 'red'));
Or with config:
var coolors = require('coolors');
console.log(coolors('My cool console log', {
text: 'yellow',
background: 'red',
bold: true,
underline: true,
inverse: true,
strikethrough: true
}));
And seems really funny to extend:
var coolors = require('coolors');
function rainbowLog(msg){
var colorsText = coolors.availableStyles().text;
var rainbowColors = colorsText.splice(3);
var lengthRainbowColors = rainbowColors.length;
var msgInLetters = msg.split('');
var rainbowEndText = '';
var i = 0;
msgInLetters.forEach(function(letter){
if(letter != ' '){
if(i === lengthRainbowColors) i = 0;
rainbowEndText += coolors(letter, rainbowColors[i]);
i++;
}else{
rainbowEndText += ' ';
}
});
return rainbowEndText;
}
coolors.addPlugin('rainbow', rainbowLog);
console.log(coolorsExtended('This its a creative example extending core with a cool rainbown style', 'rainbown'));
View Coolors module
I created my own module, StyleMe. I made it so I can do much with little typing. Example:
var StyleMe = require('styleme');
StyleMe.extend() // extend the string prototype
console.log("gre{Hello} blu{world}!".styleMe()) // Logs hello world! with 'hello' being green, and 'world' being blue with '!' being normal.
It can also be nested:
console.log("This is normal red{this is red blu{this is blue} back to red}".styleMe())
Or, if you dont want to extend the string prototype, you can just any of the 3 other options:
console.log(styleme.red("a string"))
console.log("Hello, this is yellow text".yellow().end())
console.log(styleme.style("some text","red,bbl"))
You can also use colorworks.
Usage:
var cw = require('colorworks').create();
console.info(cw.compile('[[red|Red message with a [[yellow|yellow]] word.]]'));
To make life easier, you can also make a function with it.
function say(msg) {
console.info(cw.compile(msg));
}
Now you can do:
say(`[[yellow|Time spent: [[green|${time}]]ms.]]`);
I've made a file in my snippets directory called styles.js, and I think it might help anybody who wants to import a single file.
It's a small modification to the styles.js file of color.js and has helped me a lot.
Here's the file's contents:
// Original: https://github.com/Marak/colors.js/blob/master/lib/styles.js
const styleCodes = {
// Reset all styles.
reset: [0, 0],
// Text styles.
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29],
// Foregound classic colours.
fgBlack: [30, 39],
fgRed: [31, 39],
fgGreen: [32, 39],
fgYellow: [33, 39],
fgBlue: [34, 39],
fgMagenta: [35, 39],
fgCyan: [36, 39],
fgWhite: [37, 39],
fgGray: [90, 39],
// Foreground bright colours.
fgBrightRed: [91, 39],
fgBrightGreen: [92, 39],
fgBrightYellow: [93, 39],
fgBrightBlue: [94, 39],
fgBrightMagenta: [95, 39],
fgBrightCyan: [96, 39],
fgBrightWhite: [97, 39],
// Background basic colours.
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
bgGray: [100, 49],
bgGrey: [100, 49],
// Background bright colours.
bgBrightRed: [101, 49],
bgBrightGreen: [102, 49],
bgBrightYellow: [103, 49],
bgBrightBlue: [104, 49],
bgBrightMagenta: [105, 49],
bgBrightCyan: [106, 49],
bgBrightWhite: [107, 49],
};
// This object will contain the string representation for all style codes.
const styles = {};
// Loop over all the style codes and assign them to the `styles` object.
//
// The a `styleCode` in the `styleCodes` object consists of two numbers:
// Index 0: The opening style code (In HTML this can be the opening <b> tag).
// Index 1: The closing style code (In HTML this can be the closing </b> tag).
for (let styleCode of Object.keys(styleCodes)) {
styles[styleCode] = {
open: `\x1B[${styleCodes[styleCode][0]}m`,
close: `\x1B[${styleCodes[styleCode][1]}m`,
};
}
module.exports = styles;
It's actually quite simple to use.
const styles = require("/path/to/styles.js");
// Let's say we've got an error:
const errorOpen = styles.bold.open + styles.bgRed.open + styles.fgWhite.open;
const errorClose = styles.reset.close; // Close everything
console.log(errorOpen, "ERROR", errorClose, ": Missing semicolon at line 9.");
2017:
Simple way, adding time color to the message, you don't need to change your code, use keep your console.log('msg') or console.err('error')
var clc = require("cli-color");
var mapping = {
log: clc.blue,
warn: clc.yellow,
error: clc.red
};
["log", "warn", "error"].forEach(function(method) {
var oldMethod = console[method].bind(console);
console[method] = function() {
oldMethod.apply(
console,
[mapping[method](new Date().toISOString())]
.concat(arguments)
);
};
});
If you are using Windows CMD then go to the terminal Properties/Colors (CMD top left) and then redefine the RGB value of the offensive color. In my case I believe it's the fifth color square from the left, which I changed to (222,222,222). It does not matter if the currently selected radio button shows Screen Text or Screen Background as you just redefine that specific "system" color. Once you changed the color don't forget to select back the preferred color for the background or text before clicking OK.
After the change all these reddish messages from Node (Ember in my case) are clearly visible.
In ubuntu you can simply use color codes:
var sys = require('sys');
process.stdout.write("x1B[31m" + your_message_in_red + "\x1B[0m\r\n");
node-colorify
Provides functions to print texts in color and also to do text formatting such as bold, blink, etc..

Resources