Can I fill a rectangle with a transparent gradient javascript canvas? - javascript

I'm trying to overlay this black rectangle:
By filling another rectangle of the same size on top of it that has a semi-transparent, gradient paint (should look something like this):
I know I can do a transparent paint with the following:
g2d.fillStyle = "rgba(100, 3, 3, 0.5)";
I also know how to do a gradient paint:
var grd=g2d.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"red");
grd.addColorStop(1,"blue");
g2d.fillStyle=grd;
However, I do not know how to combine both the gradient and transparency properties together as one paint to use on my rectangle. How can I do this?

There are two ways:
Global alpha
Set global (consider it a "master alpha") right before drawing something:
ctx.globalAlpha = 0.5; // [0, 1]
ctx.fillRect( ... );
Color alpha
Or define the colors themselves with alphas:
grd.addColorStop(0, "rgba(255,0,0, 0.5)"); // 50% alpha
grd.addColorStop(1, "rgba(0,0,255, 0.5)");
Worth to notice: if you use the latter approach and for example set 0% opacity on one end, the color will still matter as it is interpolated to the point where it becomes fully transparent. In the meanwhile the color definition will bleed through. I.e. don't just set black (unless black is what you need).

First draw the gradient:
var grd=g2d.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"red");
grd.addColorStop(1,"blue");
g2d.fillStyle=grd;
Then draw the semi-transparent background:
g2d.fillStyle = "rgba(200,0,0,0.5)";
g2d.fillRect(x,y,w,h);

Related

Is there an opacity setting in javascript's p5 library?

I'm using the p5 library so functions like fill() rect() ellipse() but is there a way to change the opacity of a shape so even if I fill() it I can still see the shapes behind it?
You need to fill the shape with a transparent color. The fill() color can be specified in many different ways. For instance with the 3 color channels (red, green, blue) and the alpha channel.
e.g.: Red color 50% transparency
fill(255, 0, 0, 127);
Refer to the fill documentation for all of the different options.
I'm not certain if you're creating color variables, but using setAlpha could help to adjust the alpha value only as needed. If you just need to set the alpha when you set the color, Rabbid76's answer will do just fine.
Below is an example borrowed from the setAlpha reference page.
var squareColor;
function setup() {
createCanvas(400, 400);
// assign our color variable to change the alpha later
squareColor = color(100, 50, 100);
}
function draw() {
clear();
background(200);
// In the default RGB mode the transparency (alpha) value range is between 0 and 255
squareColor.setAlpha(128 + 128 * sin(millis() / 1000));
fill(squareColor);
rect(20, 20, 60, 60);
}
<script src="https://cdn.jsdelivr.net/npm/p5#1.4.0/lib/p5.min.js"></script>
What you have to do is give the shapes a transparent color, so then you can see behind the shapes.
background(220);
// The color of the first Shape
// The first parameter is the redness, the second is the greenness, the third is the blueness, and the fourth parameter is called "Alpha" which determines the transparency
fill(255,0,0,50);
// The first Shape
circle(200,200,200);
// The color of the second Shape
fill(0,255,0,50);
// The second shape
circle(200,200,150)
If what you're asking is just to see the outline of the shapes, you can simply draw the smaller shapes on the canvas AFTER you draw the larger shapes. Nonetheless, I would recommend reading this article.

Can not change the background to white in the Canvas animation

I found a Canvas animation that fits my site, but I can't remove the background from it (or replace it with white) when replacing the background with a light one, the animation disappears immediately.
I'm just starting to get acquainted with Canvas, so do not swear much.
Here is a normal background (line 162): https://codepen.io/obiwan-kenobi/pen/vQyBxP
drawGradient ({ctx, canvas, bounds}) {
ctx.fillStyle = '# 252f3d';
ctx.fillRect (... bounds.params); }
But with white (I made it gray so that the animation could be seen, but on white there are none at all, line 162): https://codepen.io/obiwan-kenobi/pen/GwNKYg
drawGradient ({ctx, canvas, bounds}) {
ctx.fillStyle = '# e2e1e1';
ctx.fillRect (... bounds.params); }
the example you posted uses a particular compositing operation named "screen" that always result in a lighter color. Since there is no lighter color than white all shapes are invisible on a white background.
To solve your specific problem you may change the value of this property from "screen" to "multiply" and your background to white:
// row #162
ctx.fillStyle = '#FFFFFF';
/// .....
// row #450:
ctx.globalCompositeOperation = 'multiply';
Demo
All available values for this property can be found here --> globalCompositeOperation reference

how to update a radial gradient fill color in EaselJS

I am constructing a radial gradient filled circle in easelJS for a javascript canvas animation:
const blur1 = new createjs.Shape();
const endColor = this.hexToRGBA(data.settings.startColor,0);
blur1.circleCmd = blur1.graphics.beginRadialGradientFill([data.settings.startColor,endColor], [.25, .9], 0, 0, 0, 0, 0, 50).command;
blur1.graphics.drawCircle(0,0,50);
I am using the command function so that I can later update that fill.
In a request animation frame, I'd like to be able to say update the fill of this circle to the current color - a color value I'm tweening. So I have:
thisBlur1.circleCmd.style.props.colors[0] = curColor;
thisBlur1.circleCmd.style.props.colors[1] = this.hexToRGBA(curColor,0);
I see that it sets the properties of the circle properly, but it doesn't update the color on the screen, so I'm guessing that the style.props.colors array is read-only? Or maybe I need to just completely redraw the circle each frame? I'd like to avoid that, as there are a number of other properties which can change at any frame for this circle.
How do I update the gradient fill of a circle in easelJS?
Your approach is pretty close. You can't modify gradient properties directly due to how the Canvas creates gradients. Instead, call the radialGradient function on your fill command:
thisBlur1.circleCmd.radialGradient([...newColors], [.25, .9], 0, 0, 0, 0, 0, 5);
I recently answered a question about tweening gradients, which you can read here: How to animate an EaselJS gradient using TweenJS?

Javascript Canvas fillRect transparent black

I'm developing a resource monitor with JavaScript, and I pretend to complete it with an cool background animation.
I'm having trouble with fillRect and transparent colors in fillStyle, eg.:
function draw() {
ctx.fillStyle = "rgba(0, 0, 0, 0.1)";
ctx.fillRect(0, 0, c.width, c.height);
ctx.fillStyle = "#00FF00";
ctx.strokeStyle = "#00FF00";
ctx.beginPath();
ctx.arc(getRandom(0, c.width),getRandom(0,c.height),25,0,2*Math.PI);
ctx.arc(getRandom(0, c.width),getRandom(0,c.height),25,0,2*Math.PI);
ctx.stroke();
}
It works fine, but it doesn't fill completely, leaving some "ghosts" where circles already passed before.
There is anyway to fix this and make background pure black again?
Notes:
I can't draw pure black, because I want the drawed lines smoothly disappear
Image of the problem: http://i.stack.imgur.com/GrPxX.png
Note that yellow dots are most recent lines, orange are transitional lines, which give the smooth effect, and red dot are the "ghosts"
When you fill the rectangle, you're using a semi-transparent black. What that will do is to darken what's there, but it won't obliterate it, because it's semi-transparent. If you want to cover it up with pure black, either set full opacity (max alpha value), or else use an rgb colour rather than rgba. If you use rgb, the alpha value will implicitly be set to opaque.

How would you create a gradient solely with Javascript (no css) that goes from black to white?

Any help? I am new to Javascript. It is just an interesting question I saw online and I am curious possible solutions.
Thanks!
An example using canvas:
var
canvas = document.getElementById('gradient'),
context = canvas.getContext('2d'),
gradient = context.createLinearGradient(0, 0, 0, canvas.height);
gradient.addColorStop(0, '#ffffff');
gradient.addColorStop(1, '#000000');
context.fillStyle = gradient;
context.fillRect(0, 0, canvas.width, canvas.height);
(demo)
Or by filling the DOM with elements: http://jsfiddle.net/UYxs7/1 (technically this is CSS)
Well black is the hex value #000000 and white the value #FFFFFF, to make things easier we can represent this in decimal values as RGB (0,0,0) and RGB (255,255,255).
You can then use a multitude of approaches varying the colour value as you go in equal amount between R G and B creating a range of gray scale colours.
You could do this on a canvas, you could even do it using a div for each pixel, or you could just use an image if CSS isn't an option. Using divs per pixel is an option but in my opinion really not a very good one.
Pseudo code:
for i = 0 to 255 {
create div 1/255th of the height of the container and set its background colour to RGB(i,i,i)
}
The problem with this is you will still have to use CSS since styling a DIV can not be done without.
The only possible way to do it completely without CSS would be to use images. If you wanted to dynamically create gradients using images you could even go as far as having images for each grayscale colour and using these in img tags. Again you would not be able to use background images etc since this is CSS too.

Categories