JavaScript Changing BG Color - javascript

I made a div with background-color set to rgb(0,0,0); and I want to change it's color on click with javascript. I made a function to do that.
function change(){
var x = 1;
var y = x + 100;
document.getElementById("box").style.backgroundColor = "rgb(" + y + "," + y + "," + y + ")"; }
It works fine but I can change the div's color just once. What I want to do is get div's color value and set it to x and run the function again. So the bg will go like black->grey->white on each click. Depending on the y variable.
I can get the div's value but it'll get it in "rgb(0,0,0);" format. I don't know what to do after getting this. How do I manipulate just integers in rgb(0,0,0); ?

You can store current x value in data attributes:
function change(box) {
var x = +box.getAttribute('data-x'), // +box.dataset.x for modern browsers
y = x + 100;
box.style.backgroundColor = "rgb(" + y + "," + y + "," + y + ")";
box.setAttribute('data-x', y);
}
HTML
<div id="box" onclick="change(this)"></div>
Demo: http://jsfiddle.net/Wuz75/

Instead of trying to analyse the color, since your colors will be static, just make an array of colors, and keep track of the index.
var colors = [
"rgb(0,0,0)",
"rgb(100,100,100)",
"rgb(255,255,255)"
],
c = 0;
Then in your function, use c to get the next color, and then increment, or reset to 0.
function change() {
document.getElementById("box").style.backgroundColor = colors[c];
c = ++c % colors.length;
}
So whenever you run the function, it'll switch between colors in the Array.

Or you can use :
function change(x) {
var el = document.getElementById('color');
var rgb = el.style.backgroundColor.replace(/rgb|\(|\)|\s/g, '').split(',');
if ( rgb == "" ) { rgb = [0,0,0] };
for (var a = 0; a < rgb.length; a++ ) {
rgb[a] = parseInt(rgb[a]) + x;
}
el.style.backgroundColor = 'rgb('+rgb.join(',')+')';
}
Here is a demo : http://jsbin.com/ozepaz/1/edit

Related

JS Canvas - Filling a bean-shaped polygon

I have a problem with JS canvas ctx.fill() filling outside of my polygonal shape.
Here's how my code works :
ctx.beginPath()
// Here are for loops that draws a the closed shape using
ctx.stroke();
ctx.fill();
Here are the for loops:
var sx1, sy1, ex1, ey1, sx2, sy2, ex2, ey2;
for(var i = 0; i < n; i += Math.floor(n/steps)){
var radius = Math.exp(-2*i/n)*rmax+rmin;
radius += frequencyData[i]/255*(n-i + 200)/n*50;
var angle = -Math.PI/2 - i/n*2*Math.PI;
var x = radius*Math.cos(angle) + w/2+rmin/2;
var y = radius*Math.sin(angle) + (h-110)/2+rmin/2 + analyser_offset;
if (i == 0) {
gctx.moveTo(x,y);
sx1 = x;
sy1 = y;
}else if (i == n-1){
ex1 = x;
ey1 = y;
}else{
gctx.lineTo(x,y);
}
spd += frequencyData[i];
}
for(var i = 0; i < n; i += Math.floor(n/steps)){
var radius = Math.exp(-2*i/n)*rmax+rmin;
radius -= frequencyData[i]/255*(n-i + 200)/n*50;
var angle = -Math.PI/2 - i/n*2*Math.PI;
var x = radius*Math.cos(angle) + w/2+rmin/2;
var y = radius*Math.sin(angle) + (h-110)/2+rmin/2 + analyser_offset;
if (i == 0) {
gctx.moveTo(x,y);
}else if (i == 20){
sx2 = x;
sy2 = y;
}else if (i == n-1){
ex2 = x;
ey2 = y;
} else {
gctx.lineTo(x,y);
}
}
gctx.moveTo(sx1, sy1);
gctx.lineTo(sx2, sy2);
gctx.moveTo(ex1, ey1);
gctx.lineTo(ex2, ey2);
So the first for loop draws the outter side of the shape, the second for loop draws the inner side. And then the sx1, sy1, ex1, ey1, sx2, sy2, ex2, ey2 variables are here to ensure that in the last 4 lines, it closes the shape (by adding vertical line between the outter and inner lines). Maybe this problem happens because I draw the lines in an unusual order? (like drawing a rectangle by starting with 2 horizontal lines and then adding 2 vertical ones)
Here's what I get after the fill() :
And this is what I would like to have:
So could you guide me on how I'm supposed to achieve this?
Ok I fixed it by making the second loop go in the reverse order like this: for (var i = n-1; i >= 0; i -= Math.floor(n/steps)) so it draws the polygon in a more usual order and that works! I don't even need to close it using the last 4 lines which was what I wanted so that's great!

javascript generate similar random color (shader || Tint || Monochromatic )

(HI) I am not a specialist in colorimetry, but I would like to know how to realize a script that generates random colors, but based on a master color.
maybe the random Shades or Tints
Ex:of #f25f9a.
http://www.color-hex.com/color/f25f9a
#f25f9a
#f36fa4
#f47eae
#f58fb8
#f79fc2
#f8afcc
#f9bfd6
#fbcfe0
#fcdfea
#fdeff4
#ffffff
so i need to make a random color
function colors() { return ('0x' + Math.floor(Math.random() * 16777215).toString(16) || 0xffffff) };
and after that convert it to hex
function ColorToHex(hexb){return '#'+hexb.slice(2);}
then generate random tint or shader or Monochromatic Colors based on the ColorToHex
it for a plugin developement with frames for debugging sprite.
thank for help , if you know any snippets?.
You could take the delta of a single color to 255 as variable part for random multiplication. Take the same random value for every color and build a string in the wanted format.
function getRandomColor(color) {
var p = 1,
temp,
random = Math.random(),
result = '#';
while (p < color.length) {
temp = parseInt(color.slice(p, p += 2), 16)
temp += Math.floor((255 - temp) * random);
result += temp.toString(16).padStart(2, '0');
}
return result;
}
var color = '#f25f9a',
i,
rc;
for (i = 0; i < 10; i++) {
rc = getRandomColor(color);
document.body.innerHTML += '<div style="background-color: ' + rc + ';">' + rc + '</div>';
}
I'm not sure it is really what is being asked (I'm still not sure what is being asked) and I'm almost sure it will make colorimetry guys angry, but here is a lazy (i.e non-mathy) way to achieve something similar:
This solution uses an offscreen canvas to draw a gradient, and then extract the pixels from this gradient.
// returns an array of CSS color strings
// #from: CSS color string of first color
// #to: CSS color string of last color
// #numberOfShades: number of shades to be returned (from and end included)
function getGradColors(from, to, numberOfShades){
// generate a canvas context and store it in cache
var ctx = getGradColors.ctx || (getGradColors.ctx = document.createElement('canvas').getContext('2d'));
// set our canvas dimensions according to the number of shades required
var w = ctx.canvas.width = numberOfShades || 10;
ctx.canvas.height = 1;
// create a linear gradient
// (to keep 'from' and 'to' values, we set its x to 1 and width to width -1)
var grad = ctx.createLinearGradient(1,0,w-1, 0);
grad.addColorStop(0, from || 'white');
grad.addColorStop(1, to || 'black');
ctx.fillStyle = grad;
ctx.fillRect(0,0,w,1); // draw it
var data = ctx.getImageData(0,0,w,1); // get the pixels info ([r, g, b, a, r, g...])
var colors = [];
data.data.forEach(function(comp, i){
if(i%4===0){ // map each pixel in its own array
colors.push([]);
}
if(i%4===3){ // alpha
comp /= 255;
}
colors[colors.length - 1].push(comp);
});
return colors.map(function(c){
// return a CSS computed value
ctx.fillStyle = 'rgba('+c.join()+')';
return ctx.fillStyle;
});
}
var shadesOfWhite = getGradColors('#f25f9a', 'white', 10);
console.log('to white: ', shadesOfWhite);
shadesOfWhite.forEach(generateSpan);
container.appendChild(document.createElement('br'));
var shadesOfBlack = getGradColors('#f25f9a', 'black', 10);
console.log('to black: ', shadesOfBlack);
shadesOfBlack.forEach(generateSpan);
function generateSpan(color){
var span = document.createElement('span');
span.style.backgroundColor = color;
container.appendChild(span);
}
#container > span{
width: 10vw;
height: 5vw;
display: inline-block;
}
body{margin: 0}
<div id="container"></div>
let randomColor = Math.ceil((Math.random() * Math.pow(255, 3))).toString(16);
while (randomColor.length < 6) {
randomColor = '0' + randomColor;
}
randomColor = '#' + randomColor;

How to rotate images (360 degree with up and down) in javascript

I try to create a images rotate 360 degree in javascript which is working with left to right perfectly but when I try to move it with bottom to top and top to bottom then it didn't work perfectly I want to create such a demo which show in example
http://www.ajax-zoom.com/examples/example28_clean.php
e(f).mousemove(function(e)
{
if (s == true) dx(e.pageX - this.offsetLeft,e.pageY - this.offsetTop);
else o = e.pageX - this.offsetLeft; f = e.pageY- this.offsetTop;
});
function dx(t,q) {
console.log("t.....x. px.."+t+" -"+ px +"-----q---------y------"+q);
if(f - q > 0.1)
{
f = q;
a="left-top/";
i=43;
r = --r < 1 ? i : r;
e(u).css("background-image", "url(" + a + r + "." + c + ")")
//r = --r < 1 ? i : r;
// e(u).css("background-image", "url(" + a + 73 + "." + c + ")")
}else if (f - q < -0.1) {
f = q;
a="left-top/";
i=43;
r = ++r > i ? 1 : r;
e(u).css("background-image", "url(" + a + r + "." + c + ")")
}
if (o - t > 0.1) {
o = t;
r = --r < 1 ? i : r;
e(u).css("background-image", "url(" + a + r + "." + c + ")")
} else if (o - t < -0.1) {
o = t;
r = ++r > i ? 1 : r;
e(u).css("background-image", "url(" + a + r + "." + c + ")")
}
}
Where : a is path of images folder, r is number of images(1,2,3,4....) and c is .png file
But it is not working perfectly so can Anyone help me...
I think u r pointing out the glitchy movement... U just have to add more images with more perspective
This is one way of doing it by creating a function that converts a view into a Image url. The view has the raw viewing angles and knows nothing about the image URL format or limits. The function createImageURL converts the view to the image URL and applies limits to the view if needed.
An animation function uses the mouse movement to update the view which then calls the URL function to get the current URL. I leave it to you to do the preloading, T
So first Create the vars to hold the current view
const view = {
rotUp : 0,
rotLeftRigh : 0,
speedX : 0.1, // converts from pixels to deg. can reverse with neg val
speedY : 0.1, // converts from pixels to deg
};
Create a function that will take the deg rotate (left right) and the deg rotate up (down) and convert it to the correct image URL.
// returns the url for the image to fit view
function createImageURL(view){
var rotate = view.rotLeftRight;
var rotateUp = view.rotUp;
const rSteps = 24; // number of rotate images
const rStepStringWidth = 3; // width of rotate image index
const upStep = 5; // deg step of rotate up
const maxUp = 90; // max up angle
const minUp = 0; // min up angle
const rotateUpToken = "#UP#"; // token to replace in URL for rotate up
const rotateToken = "#ROT#"; // token to replace in URL for rotate
// URL has token (above two lines) that will be replaced by this function
const url = "http://www.ajax-zoom.com/pic/zoomthumb/N/i/Nike_Air_#UP#_#ROT#_720x480.jpg";
// make rotate fit 0-360 range
rotate = ((rotate % 360) + 360) % 360);
rotate /= 360; // normalize
rotate *= rSteps; // adjust for number of rotation images.
rotate = Math.floor(rotate); // round off value
rotate += 1; // adjust for start index
rotate = "" + rotate; // convert to string
// pad with leading zeros
while(rotate.length < rStepStringWidth) {rotate = "0" + rotate }
// set min max of rotate up;
rotateUp = rotateUp < upMin ? upMin : rotateUp > upMax ? upMax : rotateUp;
view.rotUp = rotateUp; // need to set the view or the movement will
// get stuck at top or bottom
// move rotate up to the nearest valid value
rotateUp = Math.round(rotateUp / upStep) * upStep;
// set min max of rotate again as the rounding may bring it outside
// the min max range;
rotateUp = rotateUp < upMin ? upMin : rotateUp > upMax ? upMax : rotateUp;
url = url.replace(rotateUpToken,rotateUP);
url = url.replace(rotateToken,rotate);
return url;
}
Then in the mouse event you capture the movement of the mouse.
const mouse = {x : 0, y : 0, dx : 0, dy : 0, button : false}
function mouseEvents(e){
mouse.x = e.pageX;
mouse.y = e.pageY;
// as we dont process the mouse events here the movements must be cumulative
mouse.dx += e.movementX;
mouse.dY += e.movementY;
mouse.button = e.type === "mousedown" ? true : e.type === "mouseup" ? false : mouse.button;
}
And then finally the animation function.
function update(){
// if there is movement
if(mouse.dx !== 0 || mouse.dy !== 0){
view.rotUp += mouse.dy * view.speedY;
view.rotLeftRight += mouse.dx * view.speedX;
mouse.dx = mouse.dy = 0;
// get the URL
const url = createImageURL(view);
// use that to load or find the image and then display
// it if loaded.
}
requestAnimationFrame(update);
}
requestAnimationFrame(update);
he createImageURL could also be used to create a referance to an image in an object.
const URLPart = "http://www.ajax-zoom.com/pic/zoomthumb/N/i/Nike_Air_"
const allImages = {
I_90_001 : (()=>{const i=new Image; i.src=URLPart+"_90_001_720x480.jpg"; return i;})(),
I_90_002 : (()=>{const i=new Image; i.src=URLPart+"_90_002_720x480.jpg"; return i;})(),
I_90_003 : (()=>{const i=new Image; i.src=URLPart+"_90_003_720x480.jpg"; return i;})(),
... and so on Or better yet automate it.
And in the createImageURL use the URL to get the property name for allImages
replacing
const url = "http://www.ajax-zoom.com/pic/zoomthumb/N/i/Nike_Air_#UP#_#ROT#_720x480.jpg";
with
const url = "I_#UP#_#ROT#";
then you can get the image
const currentImage = allImages[createImageURL(view)];
if(currentImage.complete){ // if loaded then
ctx.drawImage(currentImage,0,0); // draw it
}

Adobe Extend Script Toolkit - UnitValue changes in final IF statement?

this is my first post on here. I am a beginner at java and extendscript.
I am using this script to find black pixels in a 100x100 grid which it scans line by line. X followed by Y increment.
But when it gets to the end of the first line of 10 it loses the x px unit value, then it loses the y px unit value. it still works but I am wondering if they are numbers or unit values..?
#target photoshop
app.bringToFront();
app.preferences.rulerUnits = Units.PIXELS;
//Removes All Color Samplers
app.activeDocument.colorSamplers.removeAll();
// Show Color Sampler/ I don't know how to do this with extend script - generated in console with script listner
// =======================================================
var idShw = charIDToTypeID( "Shw " );
var desc80 = new ActionDescriptor();
var idnull = charIDToTypeID( "null" );
var list40 = new ActionList();
var ref68 = new ActionReference();
var idLyr = charIDToTypeID( "Lyr " );
var idBckg = charIDToTypeID( "Bckg" );
ref68.putProperty( idLyr, idBckg );
list40.putReference( ref68 );
desc80.putList( idnull, list40 );
executeAction( idShw, desc80, DialogModes.NO );
// =======================================================
//Gets Document Width & Height
var docWidth = activeDocument.width.as('px');
var docHeight = activeDocument.height.as('px');
//Default x Position - as a Unit Value in pixels needed for sampler position
var xPosition = new UnitValue( 0, 'px' );
var yPosition = new UnitValue( 0, 'px');
//End point Var - NOT USED
//var xEndPoint = activeDocument.width.as('px');
//var yEndPoint = activeDocument.height.as('px');
//Comparison Color Variables [Kind of like a crude memory, add more for more comparison, or recognized perception]
var WhiteColor = new RGBColor(); // initial default colour
WhiteColor.red = 255; // rest of the values default to 0
WhiteColor.green = 255;
WhiteColor.blue = 255
var BlackColor = new RGBColor(); // initial default colour
BlackColor.red = 0; // rest of the values default to 0
BlackColor.green = 0;
BlackColor.blue = 0;
//======================================================================
while( xPosition < docWidth &&
yPosition < docHeight){ // If the position of the sampler x is less than the doc width x Height - Stops at end of Doc
//Adds a color sampler
var sample = activeDocument.colorSamplers.add( [ xPosition + .5 , yPosition + .5 ] ); // X, Y position, Y position is set at 0 does not change**
app.backgroundColor=sample.color; //Sets thte background color to the sample color, maybe their could be a better way to store this
var colorB = new RGBColor(); // New color var to store background color
colorB = app.backgroundColor; //Assigns the background color to previous declare var
//Nested IF else statements
//Notes* Alerts Sampled Color - need to store this info, I don't know if I should store this as a RGB value?
// White Pixel detect
if (colorB.rgb.red === WhiteColor.red &&
colorB.rgb.blue === WhiteColor.blue &&
colorB.rgb.green === WhiteColor.green)
{
//alert("White Pixel");
}
// Black Pixel detect
else if (colorB.rgb.red === BlackColor.red &&
colorB.rgb.blue === BlackColor.blue &&
colorB.rgb.green === BlackColor.green)
{
alert("Black Pixel " + "x : " + xPosition + " y : " + yPosition + '\n'
+ "R = " + (colorB.rgb.red) + '\n'
+ "G = "+ (colorB.rgb.green) + '\n'
+ "B = "+ (colorB.rgb.blue));
}
// Other Pixel detect - Error option
else {
alert("Other Color");
}
//Final process
app.activeDocument.colorSamplers.removeAll(); //Removes the sampler so that there arn't to many
xPosition++; //increases the position by one, this is the end of the loop, starts again until while statement is void
//Once it arrives at the end of the line, increase y -value & reset x position
if (xPosition == docWidth) {
xPosition = xPosition - docWidth;
yPosition++;
}
} //bottom bracket of while statement
//======================================================================
Is x && y = z valid javascript?
When running the below code in ESTK it returns undefined.
var x,y;
// x = y = 12; // returns 12
x && y = 13; // returns undefined
$.writeln(x);
It gets even stranger when I comment out the third line and comment in the second. The result is then:
12
After that comment out the second and comment in the third again and the result still is:
12
This stays until I restart ESTK.
Anyway. I never saw a expression like x && y = z in JS. This could be your error.

Using javascript to change rgb value of background onclick

I'm trying to implement a very simple JavaScript program: every time you click the button, the RGB values of the background color are randomized.
Here's the Javascript:
function change() {
var x = Math.floor(Math.random() * 256); // range is 0-255
var y = Math.floor(Math.random() * 256);
var z = Math.floor(Math.random() * 256);
var thergb = "'rgb(" + x + "," + y + "," + z + ")'";
console.log(thergb);
document.body.style.background=thergb;
}
I'm pretty sure the problem is in how I hack together the thergb variable, but there are no errors in the console so I'm not quite sure. I log the console just to make sure it's giving me an actual random rgb, which it is.
Here's the full JSFiddle: http://jsfiddle.net/L92bY/
You have wrapped it in ' .. why ?
If you remove that it works..
var thergb = "rgb(" + x + "," + y + "," + z + ")";
Demo at http://jsfiddle.net/gaby/L92bY/9/
(you also needed to define the change function in the head tag and not in the onLoad event..)
The CSS syntax for an rgb() value does not include single quotes.
Change 'rgb(x,y,z)' to rgb(x,y,z).
Two things:
You need to choose one of the "nowrap" options for where the fiddle server puts your code.
You need to get rid of the single-quote characters around your "rgb()" expression.
var thergb = "rgb(" + x + "," + y + "," + z + ")";
Personally I'd set "backgroundColor" instead of just "background", but it works (in Firefox at least) to set "background".
Fixed fiddle.
Working fiddle (just corrected your code): http://jsfiddle.net/L92bY/18/
The syntax for the CSS color as rgb is rgb(r,g,b) (no extra apostrophe "'") = not 'rgb(r,g,b)'
function change() {
var x = Math.floor(Math.random() * 256); // range is 0-255
var y = Math.floor(Math.random() * 256);
var z = Math.floor(Math.random() * 256);
var thergb = "rgb(" + x + "," + y + "," + z + ")";
console.log(thergb);
document.body.style.background=thergb;
}
PS: If this is not working for you you are calling this javascript function BEFORE it was declared.
You could probably also just simplify where your code went wrong by using string template literals.
var thergb = `rgb(${x}, ${y}, ${z})`

Categories