IF: Opacity is 50% or Less Draw Circle - javascript

For one of my classes, we need to create an
if (...){
then draw something!
}
statement. However, I am super new to JavaScrip and whenever I try to create the if statement, I don't have much success.
What I am trying to do is only have a circle (by using the canvas) show if the opacity is 50% (I may change this value at a later time) or less. I have it so that the colour and opacity is randomised. I do have other shapes with this design, however, just for the purpose of this I have excluded them from the below example and JSFiddle.
Here's what I have so far: JSFiddle
var draw_optional = true;
if (ran_colours < "(0.5)"){
draw_optional = true;
context.stroke();
}
I was wondering am I doing something wrong? If you click on the JSFiddle link you can see my full code!
Thanks in advance!

ran_colours looks like this: "rgba(29,251,218,0.5617056562158282)".
what do you think, is "rgba(29,251,218,0.5617056562158282)" smaller than "(0.5)"? Right, you can't tell (I hope). You need to get the alpha value string, or precalculate the alpha-value and store it in its own variable. Second approach is much nicer, so here is how it's done:
Before you assign the rgba-color to ran_colours, add this line:
var alpha = Math.random();
In the ran_colours assignment, replace the last random-call with the alpha-variable
var ran_colours =
"rgba("
+ Math.floor(Math.random() * 256) + ","
+ Math.floor(Math.random() * 256) + ","
+ Math.floor(Math.random() * 256) + ","
+ alpha + ")";
Since alpha is just a number, you can easily write your if-statement:
if (alpha < 0.5){
draw_optional = true;
context.stroke();
}

Related

Adding additional hex colors to RGB color mixing algorithm

I already have a decent algorithm that is able to combine and mix CMYK colors together. However it is unable to combine additional hex colors without failing. I would like some help in figuring out how I can edit the algorithm to accept other colors. I know its possible to color mix several colors as I've seen it being done in other online free apps.
Another modification I'd like to make is to have the overall mixture at 100%. Currently you can max out all colors at 100% but I'd like to have it where you can only have a percentage of each color to make up to 100%.
Full code can be found here:
https://jsfiddle.net/5dsgbne9/30/
Heres the main color mixing algorithm which needs to be modified
var slider = new Slider('#ex1', {
formatter: function(value) {
return 'Current value: ' + value;
}
});
var colorPercentages = {};
var colors = document.getElementsByClassName("colors");
for (let i = 0; i < colors.length; i++) {
if (!(colors[i].getAttribute("id") in colorPercentages)) {
colorPercentages[colors[i].getAttribute("id")] = 0;
}
colors[i].addEventListener("click", function() {
colorPercentages[colors[i].getAttribute("id")] = $("#ex1").val();
colors[i].innerHTML = colors[i].getAttribute("id") + " " + $("#ex1").val() + "%";
console.log(colorPercentages)
//formula here!!
let r = 255 * (1 - colorPercentages.Cyan / 100) * (1 - colorPercentages.Black / 100);
let g = 255 * (1 - colorPercentages.Magenta / 100) * (1 - colorPercentages.Black / 100);
let b = 255 * (1 - colorPercentages.Yellow / 100) * (1 - colorPercentages.Black / 100);
$("body").css('background-color', 'rgb(' + r + ', ' + g + ', ' + b + ')');
});
}
Give my fiddle a try:
EDIT: New fiddle
https://jsfiddle.net/wg6bp210/15/
My solution requries the rgb information to be present in the element, so:
<button class="colors" id="Yellow" hexa="#ffff00">Yellow</button>
becomes
<button class="colors" id="Yellow" hexa="#ffff00" r="254" g="221" b="0">Yellow</button>
Had to basically rewrite the whole code but the fiddle does everything requested:
1) Adds selected colors and updates background color accordingly;
2) Updates percentages on buttons accordingly to a total of 100%;
3) Implemented a deactivate behavior, to deactivate the color on
click, in case it was already activated.

Color-Scales depending on how often a point gets drawn (JS Canvas)

Lately I created a project involving drawing a lot of points on a canvas to plot a strange attractor. The details of this project aren't really relevant, but if you want to see it in action, go here: How can I check if an attractor is strange?
The problem I was encountering is the following: How can I draw a point on a canvas, whose color depends on the color, that was already there? In other words: How do I implement a color scale that depends on that number of times, a specific point has been colored?
I actually found a way, but I'm not convinced if it's the best. Here is how it works:
ctx.globalCompositeOperation = "lighter";
ctx.fillStyle = "rgb(50,5,1)";
ctx.fillRect(x,y,size,size);
It simply adds to the color that is already there. This can already look pretty good:
But there are also a lot of restrictions when using this method:
I can't get a colorchange from green to red for example
Using this method on a white background is impossible
I can't create a colorscale that includes more than to "fixed points", like for example red->green->blue
Maybe you know methods that work better than mine...
I think you need to track hits per pixel to implement a function that would allow you to change picture color, rather than just luminosity or redness. As suggested above, you should use a multi-dimensional array to track hits per pixel.
var canvasPixels = [];
for (var y = 0; y < 1000; y++) {
canvasPixels[y] = [];
for (var x = 0; x < 1000; x++) {
canvasPixels[y][x] = 0;
}
}
There are any number of things you can do if you apply the color math yourself. Here I'm using a color sine wave.
function getColor(hits) {
var frequency = 0.3;
var r = Math.round(Math.sin(frequency*hits + 0) * 127 + 128);
var g = Math.round(Math.sin(frequency*hits + 2) * 127 + 128);
var b = Math.round(Math.sin(frequency*hits + 4) * 127 + 128);
return "rgb(" + r + "," + g + "," + b + ")";
}
Then, you just use this function when drawing to cycle through the rainbow.
canvasPixels[y][x]++;
ctx.fillStyle = getColor(canvasPixels[y][x]);
ctx.fillRect(x,y,size,size);

Rotation formula deforming polygons

I have written myself a formula to rotate the points of regular polygons (and maybe even irregular) around an orientation point. The formula seems to work on discretely coded rectangles:
tempShape.points = [[0,0],[wid,0],[wid,hig],[0,hig]];
But not on polygons generated by formula:
tempShape.points = [[len,0]];
for(var i=1; i < poin; i++){
if(gen){
tempShape.points[i] = [0,0];
tempShape.points[i][0] = len*Math.cos(angle*i);
tempShape.points[i][1] = len*Math.sin(angle*i);
}
}
This is my rotation formula:
for(var i2 = 0; i2 < displayList[i].points.length; i2++){
displayList[i].points[i2][0] = (displayList[i].pointsRot[i2][0] + displayList[i].oPoint[0]) * Math.cos(displayList[i].rotation) - (displayList[i].pointsRot[i2][1] + displayList[i].oPoint[1]) * Math.sin(displayList[i].rotation);
displayList[i].points[i2][1] = (displayList[i].pointsRot[i2][1] + displayList[i].oPoint[1]) * Math.cos(displayList[i].rotation) + (displayList[i].pointsRot[i2][0] + displayList[i].oPoint[0]) * Math.sin(displayList[i].rotation);
}
Where displayList[i] is the shape, .points is the array containing all the points, .rotation is the rotation of the shape, .oPoint is the point of orientation.
I hope you can help, thanks in advance.
Kyle.
Edit:
Just tried rather than incrementing the rotation I set a static rotation of 0.01, but this makes it act like it would normally if incremented the rotation by 0.01, so somewhere (I don't know where) it must be like incrementing my rotation by the set rotation, I just need to figure it out. Could I give my whole code for someone to look through to help me?
You are using in the second formula value displayList[i].pointsRot[i2][0] which has been already changed in the first formula. Just remember original value in temporary variable and use it.
Edit: It seems I was entangled in your longlonglong names.
Сheck that your formulas match to:
NewX = CenterX + (OldX-CenterX)*Cos(Fi) - (OldY-CenterY)*Sin(Fi)
NewY = CenterY + (OldX-CenterX)*Sin(Fi) + (OldY-CenterY)*Cos(Fi)
where (CenterX, CenterY) is point of rotation

map gradient to number value

I need to draw a gradient on a div/canvas or something. The gradient will start on one color and end on another. So only two colors(and the ones made up between). Lets say it starts on white and ends on black.
The application im working on calls an API that retturns a number betwenen 1-100.
The width of the gradient should be 100% i think to make the math "easy".
The number i get from the API should map to a position and hex code in the gradient and return those two.
How would i do something like that? Any ideas or code?
If i understand this correctly, you have:
startColor at 0%
endColor at 100%
chosenColor at x%
Lets assume you saved the hex colors like this (here white is the startColor):
startColor.red = 255;
startColor.green = 255;
startColor.blue = 255;
You calculate the difference in the two colors:
diffColor.red = endColor.red - startColor.red;
diffColor.green = endColor.green - startColor.green;
diffColor.blue = endColor.blue - startColor.blue;
Then you add the difference to the startColor, according to your x value:
markerColor.red = startColor.red + diffColor.red * x / 100;
markerColor.green = startColor.green + diffColor.green * x / 100;
markerColor.blue = startColor.blue + diffColor.blue * x / 100;
If you need to calculate the position it goes the same way:
markerPosition = startPosition + distance / x * 100
I have no idea if this is what you're looking for. I can't tell if your question is super complicated or really simple.

Very laggy animation in javascript

I have made a board with 156X64 divs 3 pixel each with border radius, so it looks like a board out of LED. I have string representing 0 or 1 of each 7X5 matrix of letters.
var lgeoa="00100001000001000001100011000101110";//7X5 matrix letter A
var lgeob="10000111000010001010100011000101110";//7X5 matrix letter B
and so on...
Drawing letter means change corresponding div background color. It is working fine, but after that I wanted to animate them the problem started. I clear line and draw in every 10 milliseconds, but its very very laggy. So please how can this code be optimized to work without lags?
P.S. Surprisingly it's working better in IE11 rather than in chrome.
Here is a fiddle
There's a lot of optimization that can be done here. I'll point out a couple.
Starting with the animate function, the first thing I notice is that you're running a bit of code every 10ms. Why don't we check out what's being run?
function animate() {
var string = "აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰ ტესტ ტესტ აი ემ ე თეიბლ ტექსტი იწერება აქ"; //string to animate
position = 150; //initial position of string
window.setInterval(function () {
clearLine(0);
drawOnBoard(string, position, 0);
position = position - 1;
}, 10);
}
Clearline is the first function.
function clearLine(n){
for(var i=n*symbolHeight*lineWidth+n*lineWidth;i<(n+1)*symbolHeight*lineWidth+n*lineWidth;i++)
leds[i].style.backgroundColor="black";
}
That's a bit of a mess in the for loop. My understanding is that non-compiled code will run all of that math for every single iteration. So let's move it out of the for loop.
function clearLine(n) {
var initial = n * symbolHeight * lineWidth + n * lineWidth;
var length = (n + 1) * symbolHeight * lineWidth + n * lineWidth;
for (var i = initial; i < length; i++)
leds[i].style.backgroundColor = "black";
}
Ah but there's still more to be done. I see that both equations have a lot of shared math.
function clearLine(n) {
var whateverThisIs = symbolHeight * lineWidth + n * lineWidth;
var initial = n * whateverThisIs;
var length = (n + 1) * whateverThisIs;
for (var i = initial; i < length; i++)
leds[i].style.backgroundColor = "black";
}
I saw that you're moving on so I'll stop working on this for now. There's still plenty more to optimize.
Here's a fiddle of the updated version.

Categories