well... for begining, i m building some dumb and easy projects because i'm starting learning the world of front end development. One of those you can find in internet was this Color picker idea. Some page where with a button you can generate a random color. all random, no connections between the colors o something else.
(i'm not a native english speaker so sorry if i write something and you dont get it right)
Here's the link to the repository
so...
I build a function that makes a random HSL color randomizing the values and then building a string and puting that in the css
function getRandomHsl(){
let hueValue = 0;
hueValue = Math.floor(
Math.random() * (360 + 1)
)
let satValue = 0;
satValue = Math.floor(
Math.random() * (100 + 1)
)
let lightValue = 0;
lightValue = Math.floor(
Math.random() * (100 + 1)
)
return 'hsl(' + hueValue + ', ' + satValue + '%, ' + lightValue + '%)';}
if you can give me your opinion on that function and tell me if you would have done it inanother way.
so... i wanted to find the way to if the Lightness would have a low value the color of the font change it to some white or something like that. And this is what i figured out. (the first part of the code is the button changing the value of the background color of the main div. This works well. The problem comes after).
hslBtn.addEventListener('click', () => {
let hslStringComplete = getRandomHsl();
colorShowcase.textContent = hslStringComplete;
document.getElementById('color-container').style.backgroundColor = hslStringComplete;
/*================================= change the color font od the text when its to dark */
let hslLightValue = hslStringComplete;
let lightValue = hslLightValue.toString().substr(13,3).replace(/\D/g,'')
console.log(hslLightValue.substr(13,3).replace(/\D/g,''));
if(lightValue < 40){
innerHTML('input').style.color = "white";
}})
i have really strougle it out coming up with this idea so i want some opinion on how could i have done in other way.
PD: `if(lightValue < 40){
innerHTML('input').style.color = "white";}
this is hte HTML: <input class="background-container"><h3 class="forWhiteColor">Background Color : <span class="color-showcase">#messi</span></h3></input>
this part get me an error and the html doesn get changes. Here's the error.
console error
thanks in advance.
innerHTML('input') should probably be document.getElementById('color-container') instead.
also you should note that when you extract a part of a string, you get a string.
And comparing a string to a number won't work well, you first need to convert your string to a number with parseInt (for integers) or parseFloat (for float)
Related
The following is a line I have in my Javascript code. It outputs -5108024 and some change when sqftVal = 2828 and bathsVal = 3.5.
out.value = -6932000 + 221400 * Math.log(sqftVal) + 637.2*Math.exp(bathsVal) + 51640;
However, when I manually type this in my calculator, I get roughly -5099721 and some change. I get the same result in R. Why does JavaScript mess up the math, and what can I do to fix this?
Calculator/R input:
-6932000 + 221400 * ln(2828) + 637.2 * e^(3.5) + 51640 = -5099721.073
I don't believe this is a floating point error because as I add more terms, the difference becomes fairly large.
Plus, everything was matching up until I added the fourth term (+51640) which made no sense to me.
There must be some other code that is interfering with your values or something, because the code shown does not produce the value you report.
var sqftVal = 2828;
var bathsVal = 3.5;
var value = -6932000 + 221400 * Math.log(sqftVal) + 637.2*Math.exp(bathsVal) + 51640;
console.log(value);
I have a json array with words in different languages that I want to alert randomly. The thing is that I have different number of words in every language, so when I use the code below, I am getting undefined at some cases (because some words has more languages than others, and so the length property is longer than it should be).
I have tried to use all.french.length at the end of line 2, but got an error. Does anybody know what should I do?
Thanks!
all = [{"english":"cat", "french":"chat"}, {"english":"dog"}]
let z = Math.floor(Math.random() * all.length);
alert('random: ' + all[z].french);
Edit: I want it only to alert words only in the language I defined in line 3. In this case, I want only to display french words: only alert "chat" again and again. My original data of words is larger than that, of course, and has more languages, so I can't use 0.
If you just want a random element where the translation french exists you can filter your array
const filteredArray = all.filter(element =>
element.french === "" || element.french);
let z = Math.floor(Math.random() * filteredArray.length);
alert('random: ' + filteredArray[z].french);
you can do that:
const all = [{"english":"cat", "french":"chat"}, {"english":"dog"}]
function myAlert(lang)
{
let arr = all.filter( e=>!!e[lang])
, z = Math.floor(Math.random() * arr.length)
;
alert('random: ' + arr[z][lang] )
}
myAlert('french')
myAlert('english')
EDIT
I tested something out, and apparently, this:
if(info.max.value == "") {maxdesiredvalue = 999999999999999999999}
Returns in the chrome console:
> maxdesiredvalue
< 999999999
So I believe the problem really comes from there... is there a maximum number of digits we can attribute to a variable?
I'm into javascript for a few months now, and I've made a program that generates random weapons for a tabletop rpg.
Every weapon generated has a price relative to it's attributes. My problem today is that this price won't exceed 9 digits (cannot reach billion), even though it can.
In my generator, it is possible to choose certain properties before generating the weapon. If I intentionally try to generate something worth over a billion gold, it will crash instantly. On the other hand, if there is any way the weapon can be generated without exceeding the billion, it will do so.
For example, the most expansive metal is the "Residuum". The only 2 weapons that can be generated in Residuum are the dart and the shuriken, since they only use 1/16 of an Ingot. Therefore if I set the metal to be Residuum, they will be the only 2 possible generated weapons. From this point, if I try to specify I want a Residuum Sword, it will simply crash as explained earlier.
In my generation options, I also have a text input for the user to choose a minimum value and/or a maximum value for the weapon. I set the default max value to Infinity, so it should'nt be a problem.
function desiredvalue(){
if(info.max.value == "") {maxdesiredvalue = Infinity}
else {maxdesiredvalue = parseInt(info.max.value)}
if(info.min.value == "") {mindesiredvalue = 0}
else {mindesiredvalue = parseInt(info.min.value)}
}
In my html:
Min price: <input type="text" name="min" value="" onchange="desiredvalue()">
Max price: <input type="text" name="max" value="" onchange="desiredvalue()">
I already tried to deactivate this function to see if it was the problem, but even without a specific max value, weapons still won't be generated if their value exceeds 9 digits.
Maybe the problem sets inside the value formula, so here it is, even though it might not be a big help since it is all made up from variables.
WeapValue = ((((IngotValue * Ingots) + CraftTime + (actualEnchantTime * 3) + (LS * 0.02) + (R * 0.05) + BS + (FTH * 0.03)) * (((BPArace + BPAstatus + BPAlevel + ((BPAcrit1 + 1) * BPAcrit2)) / 100) + 1)) + PAenchant + PAaugment1 + PAaugment2 + PAaugment3)
Also the value is modified afterwards to fit in gold, silver or copper...
WeapValue.toLocaleString('en-US', {minimumFractionDigits: 0});
WeapValue = WeapValue.toFixed(2);
if (WeapValue >= 2) {WeapValue2 = Math.ceil(WeapValue); goldtype = " GP"}
else if (WeapValue < 2 && WeapValue >= 1) {WeapValue2 = WeapValue * 10; goldtype = " SP"}
else if (WeapValue < 1 && WeapValue >= 0) {WeapValue2 = WeapValue * 100; goldtype = " CP"}
Nothing else in the script really change the value, and all the variables affecting it are defined earlier, and I don't really think they are the problem, since they actually seem to work (they simply make the price exceed 9 digits).
If you have any questions related to the script, I'm here to answer, but I can't put the full script since it is very, very long (2543 lines)...
If anyone has an idea of how I can deal with my problem, it would be so appreciated! Again, I'm not a javascript expert, but I did my best and looked a lot on the Internet for help, but I still can't get rid of this problem...
Thank you!
Very simple code, very simple problem. When a link is pressed, it moves a div either up or down. However, I cannot get it to move incrementally. I know this is a simple syntax error, but google isn't revealing the error of my ways. Anyone willing to enlighten me?
<a class="galsel" onclick="document.getElementById('innerscroll').style.bottom -='167px';">«</a>
<a class="galsel" onclick="document.getElementById('innerscroll').style.bottom +='167px';">»</a>
I already have it so that the div tiles itself vertically, so I'm not worried about it going "too high" or "too low"
Here's what it looks like right now: drainteractive.com/FBD/projects.php
You have to parse the value from the string containing px
// Increase by 167
document.getElementById('innerscroll').style.bottom = (parseInt(document.getElementById('innerscroll').style.bottom, 10) + 167) + ' px'
// Decrease by 167
document.getElementById('innerscroll').style.bottom = (parseInt(document.getElementById('innerscroll').style.bottom, 10) - 167) + ' px'
// Abstracted
function addToBottom(el, amount) {
// You probably add lower and upper bound check conditions
el.style.bottom = (parseInt(el.style.bottom) + amount) + ' px';
}
var el = document.getElementById('innerscroll');
addToBottom(el, 167);
addToBottom(el, -167);
Also be sure to make it work for cases where bottom wasn't set initially
var currentBottom = parseInt(document.getElementById('innerscroll').style.bottom) || 0;
+='167px' will concatinate it an it will become '167px167px167px167px167px'. Not sure what will result -='167px', but probably will result an error.
You need to rip the 'px' off the string, convert(?) it to an int, then subtract from that.
onclick="var mElem = document.getElementById('innerScroll'); mCur = parseInt(mElem.style.bottom.replace('px', 0)); mElem.style.bottom = (mCur-167)+'px'"
Naturally, this should all be put into a separate function, who is then called in the onclick, rather than the monstrosity above.
function moveUp()
{
var mElem = document.getElementById('innerScroll');
var mCur = parseInt(mElem.style.bottom.replace('px', 0));
mElem.style.bottom = (mCur-167)+'px';
}
...
<strike>onlick="moveUp()"</strike>
onclick="moveUp()"
My mind must have been somewhere else..
Context: multi-user app (node.js) - 1 painter, n clients
Canvas size: 650x400 px (= 260,000 px)
For the canvas to be updated frequently (I'm thinking about 10 times a second), I need to keep the data size as small as possible, especially when thinking about upload rates.
The toDataURL() method returning a base64 string is fine but it contains masses of data I don't even need (23 bit per pixel). Its length is 8,088 (without the preceding MIME information), and assuming the JavaScript strings have 8-bit encoding that would be 8.1 kilobytes of data, 10 times per second.
My next try was using JS objects for the different context actions like moveTo(x, y) or lineTo(x, y), sending them to the server and have the clients receive the data in delta updates (via timestamps). However, this turned out to be even less efficient than the base64 string.
{
"timestamp": 0,
"what": {
"name": LINE_TO,
"args": {"x": x, "y": y}
}
}
It doesn't work fluently nor precisely because there are nearly 300 lineTo commands already when you swipe your brush shortly. Sometimes there's a part of the movement missing (making a line straight instead of rounded), sometimes the events aren't even recognized by the script client-side because it seems to be "overwhelmed" by the mass of events triggered already.
So I have to end up using the base64 string with its 8.1 KB. I don't want to worry about this much - but even if done asynchronously with delta updates, there will be major lags on a real server, let alone the occasional bandwidth overrun.
The only colors I am using are #000 and #FFF, so I was thinking about a 1-bit data structure with delta updates only. This would basically suffice and I wouldn't mind any "color" precision losses (it is black after all).
With most of the canvas being white, you could think of additional Huffman run-length encoding to reduce size even further, too. Like a canvas with a size of 50x2 px and a single black pixel at (26, 2) would return the following string: 75W1B74W (50 + 25 white pixels, then 1 black pixel, then 24 more white pixels)
It would even help if the canvas consisted of a 1-bit string like this:
00000000000000000000000000000000000000000000000000
00000000000000000000000001000000000000000000000000
That would help a lot already.
My first question is: How to write an algorithm to get this data efficiently?
The second is: How could I pass the pure binary canvas data to the clients (via node server)? How do I even send a 1-bit data structure to the server? Would I have to convert my bits to a hexadecimal (or more) number and re-parse?
Would it be possible to use this as a data structure?
Thanks in advance,
Harti
I need to keep the data size as small as possible
Then don't send the entire data. Send only the changes, close to what you propose yourself.
Make the framework such that every user can only do "actions" such as "draw black strokeWidth 2 from X1,Y1 to X2,Y2".
I wouldn't bother with some pure binary thing. If there's only two colors then that's easy to send as the string "1,2,x,y,x2,y2", which the other people will parse precisely the same way the local client will, and it will get drawn the same way.
I wouldn't overthink this. Get it working with simple strings before you worry about any clever encoding. It's worth trying the simple thing first. Maybe the performance will be quite good without going through a lot of trouble!
I sorted it out, finally. I used an algorithm to get the image data within a specified area (i.e. the area currently drawn on), and then paste the image data to the same coordinates.
While drawing, I keep my application informed about how big the modified area is and where it starts (stored in currentDrawingCoords).
pixels is an ImageData Array obtained by calling context.getImageData(left, top, width, height) with the stored drawing coordinates.
getDeltaUpdate is called upon onmouseup (yeah, that's the drawback of the area idea):
getDeltaUpdate = function(pixels, currentDrawingCoords) {
var image = "" +
currentDrawingCoords.left + "," + // x
currentDrawingCoords.top + "," + // y
(currentDrawingCoords.right - currentDrawingCoords.left) + "," + // width
(currentDrawingCoords.bottom - currentDrawingCoords.top) + ""; // height
var blk = 0, wht = 0, d = "|";
// http://stackoverflow.com/questions/667045/getpixel-from-html-canvas
for (var i=0, n=pixels.length; i < n; i += 4) {
if(
pixels[i] > 0 ||
pixels[i+1] > 0 ||
pixels[i+2] > 0 ||
pixels[i+3] > 0
) {
// pixel is black
if(wht > 0 || (i == 0 && wht == 0)) {
image = image + d + wht;
wht = 0;
d = ",";
}
blk++;
//console.log("Pixel " + i + " is BLACK (" + blk + "-th in a row)");
} else {
// pixel is white
if(blk > 0) {
image = image + d + blk;
blk = 0;
d = ",";
}
wht++;
//console.log("Pixel " + i + " is WHITE (" + blk + "-th in a row)");
}
}
return image;
}
image is a string with a header part (x,y,width,height|...) and a data body part (...|w,b,w,b,w,[...])
The result is a string with less characters than the base64 string has (as opposed to the 8k characters string, the delta updates have 1k-6k characters, depending on how many things have been drawn into the modification area)
That string is sent to the server, pushed to all the other clients and reverted to ImageData by using getImageData:
getImageData = function(imagestring) {
var data = imagestring.split("|");
var header = data[0].split(",");
var body = data[1].split(",");
var where = {"x": header[0], "y": header[1]};
var image = context.createImageData(header[2], header[3]); // create ImageData object (width, height)
var currentpixel = 0,
pos = 0,
until = 0,
alpha = 0,
white = true;
for(var i=0, n=body.length; i < n; i++) {
var pixelamount = parseInt(body[i]); // amount of pixels with the same color in a row
if(pixelamount > 0) {
pos = (currentpixel * 4);
until = pos + (pixelamount * 4); // exclude
if(white) alpha = 0;
else alpha = 255;
while(pos < until) {
image.data[pos] = 0;
image.data[pos+1] = 0;
image.data[pos+2] = 0;
image.data[pos+3] = alpha;
pos += 4;
}
currentpixel += pixelamount;
white = (white ? false : true);
} else {
white = false;
}
}
return {"image": image, "where": where};
}
Call context.putImageData(data.image, data.where.x, data.where.y); to put the area on top of everything there is!
As previously mentioned, this may not be the perfect suit for every kind of monochrome canvas drawing application since the modification area is only submit onmouseup. However, I can live with this trade-off because it's far less stressful for the server than all the other methods presented in the question.
I hope I was able to help the people to follow this question.