I'm trying to make a fade out effect with JavaScript on the Canvas element. I'm currently have two sollutions for this. In theory, both should work fine, but in practice, only one does, and I wonder why.
The not working code is the following:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var i = 1;
requestAnimationFrame(test);
function test(){
i-=0.01;
ctx.fillStyle = "white";
ctx.fillRect(20, 20, 75, 50);
ctx.globalAlpha = i;
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 75, 50);
requestAnimationFrame(test);
}
What I wanted to achieve, is to gradually change the alpha value of the current context, in order to fade it to white. After a while, it should have full transparency, but it does not. It stops right before reaching that state. Here it is in JSFiddle: https://jsfiddle.net/bq75v1mm/
The working code is the following:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var i = 1;
requestAnimationFrame(test);
function test(){
i-=0.01;
ctx.fillStyle = "white";
ctx.fillRect(20, 20, 75, 50);
ctx.fillStyle = "rgba("+255+","+0+","+0+","+i+")";
ctx.fillRect(20, 20, 75, 50);
requestAnimationFrame(test);
}
With this code, I'm just simply changing the alpha value of the given fillStyle for the upcoming rectangle, and it works like a charm, and makes the square vanish into thin air. Here it is in JSFiddle: https://jsfiddle.net/mxtynwwd/
I would like to understand why doesn't the first sollution work? Why can't I lower the globalAlpha value after a given minimum? Or is the problem in the code?
In your second example, you reset fillStyle every time before drawing the white rectangle.
You're not doing the same with globalAlpha in your first example.
Not all values will be accepted by the globalAlpha property. Quoting MDN:
A number between 0.0 (fully transparent) and 1.0 (fully opaque). The default value is 1.0 Values outside the range, including Infinity and NaN will not be set and globalAlpha will retain its previous value.
Due to precision loss in floating pointer math, when i becomes negative, globalAlpha gets stuck on 0.009999999999999247 (may vary across machines).
To fix both of the above, reset globalAlpha before drawing the white rectangle:
ctx.globalAlpha = 1;
and before drawing the red one, make sure i is >= 0:
i = i < 0 ? 0 : i;
Your first example can accordingly be updated to behave exactly like your second one:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var i = 1;
requestAnimationFrame(test);
function test() {
i -= 0.01;
i = i < 0 ? 0 : i;
ctx.globalAlpha = 1;
ctx.fillStyle = "white";
ctx.fillRect(20, 20, 75, 50);
ctx.globalAlpha = i;
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 75, 50);
requestAnimationFrame(test);
}
[ Updated fiddle ]
Related
I'm trying to place text over a background color. I think the issue is that the "fillStyle" is being applied to both the text and the background. I want the text to be black. What am I doing wrong here?
Below is my code:
var canvas = document.createElement("canvas");
canvas.width = 200;
canvas.height = 200;
var ctx = canvas.getContext("2d");
ctx.fillText("hello", 0, 0);
ctx.fillStyle = "#E7E0CA";
ctx.fillRect(0, 0, 200, 200);
var img = document.createElement("img");
img.src = canvas.toDataURL("image/png");
document.body.appendChild(img);
Here's a link to the fiddle: https://jsfiddle.net/jessecookedesign/9rsy9gjn/36/
Unlike HTML where you define a list of what you want to appear, when working with a canvas it's like you're painting. So each "drawing" operation you do (like fillRect or fillText) will go on top of any existing content and cover it up.
Similarly since you're actually painting, rather than defining objects, you need to set the fill style before drawing. Using the analogy, you need to select the color of paint you'll use before you put paint to canvas.
Finally, the fillText method takes a position as the start of the baseline of the text. Since (0, 0) is the top left of the canvas, your text will get drawn above the bounds of the canvas an not be visible, so you need to move it down e.g. fillText("Hello World", 10, 100);
Correcting for those issues you get something like the following (and skipping the steps involved in converting to an img tag):
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
// Draw a black background
context.fillStyle = "black";
context.fillRect(0, 0, 200, 200);
// Draw the text
context.fillStyle = "#E7E0CA";
context.fillText("Hello world", 10, 100);
<canvas id="canvas" width="200" height="200"></canvas>
Wrong order - You're drawing the rectangle over the text.
The text has the same color as the rectangle
There's no font specified
The position (0,0) is out of bounds
Try it like this:
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#E7E0CA";
ctx.fillRect(0, 0, 200, 200);
ctx.fillStyle = "black";
ctx.font="20px Georgia";
ctx.fillText("hello",10,30);
There are several issues:
You need to first fill the background, then fill the text.
Your text is above the canvas area — try a lower position.
This code has the correct order, and a position for the text that isn’t outside the canvas bounds.
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#E7E0CA";
ctx.fillRect(0, 0, 200, 200);
ctx.fillStyle = "#000000";
ctx.fillText("hello", 10, 10);
With the changed order, of course you need to choose a new color for the text, in this case "#000000".
Alternatively, you could save and restore your canvas state:
var ctx = canvas.getContext("2d");
ctx.save();
ctx.fillStyle = "#E7E0CA";
ctx.fillRect(0, 0, 200, 200);
ctx.restore();
ctx.fillText("hello", 10, 10);
Whenever you access canvas of html page,
whatever you draw first, will display first.
so if you want to display your colored box first fill it first, then write your text by providing color ,font and position of text. for example,
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#E7E0CA";//your rect color
ctx.fillRect(0, 0, 200, 200);//your rect size
ctx.fillStyle = "#000000";//color for your text
ctx.font="30px Arial";//font style and size
ctx.fillText("hello world",25,50);//text and location
</script>
I need to use several canvas-es with different values (see data-percent) with same reusable code block but "animation" makes it a little bit tricky. Im not sure how to make it reusable. Copy-pasting the same code over and over again is obviously a wrong move, I usually avoid it at any cost.
First thing is obviously to remove id and use class instead, then I could select all the canvas-es:
<canvas class="circle-thingy" width="120" height="120" data-percent="75"></canvas>
<canvas class="circle-thingy" width="120" height="120" data-percent="23"></canvas>
<canvas class="circle-thingy" width="120" height="120" data-percent="89"></canvas>
var allCircles = document.getElementsByClassName('circle-thingy');
But now comes the trickier part.. How about canvas JavaScript code? There's probably a very easy solution but I can't see it! Terrible time to quit smoking I guess (as always), brain is like shut down.
What I tried: for loop with allCircles list. Problem is that I cannot use setInterval and clearTimeout with this approach. Dynamic variable names? How do I reference them later?
Here's my code with a single circle, try it.
// Get canvas context
var ctx = document.getElementById('my-circle').getContext('2d');
// Current percent
var currentPercent = 0;
// Canvas north (close enough)
var start = 4.72;
// Dimensions
var cWidth = ctx.canvas.width;
var cHeight = ctx.canvas.height;
// Desired percent -> comes from canvas data-* attribute
var finalPercent = ctx.canvas.getAttribute('data-percent');
var diff;
function circle() {
diff = ((currentPercent / 100) * Math.PI * 2 * 10).toFixed(2);
ctx.clearRect(0, 0, cWidth, cHeight);
ctx.lineWidth = 3;
// Bottom circle (grey)
ctx.strokeStyle = '#eee';
ctx.beginPath();
ctx.arc(60, 60, 55, 0, 2 * Math.PI);
ctx.stroke();
// Percent text
ctx.fillStyle = '#000';
ctx.textAlign = 'center';
ctx.font="900 10px arial";
ctx.fillText(currentPercent + '%', cWidth * 0.5, cHeight * 0.5 + 2, cWidth);
// Upper circle (blue)
ctx.strokeStyle = '#0095ff';
ctx.beginPath();
ctx.arc(60, 60, 55, start, diff / 10 + start);
ctx.stroke();
// If has desired percent -> stop
if( currentPercent >= finalPercent) {
clearTimeout(myCircle);
}
currentPercent++;
}
var myCircle = setInterval(circle, 20);
<canvas id="my-circle" width="120" height="120" data-percent="75"></canvas>
Feel free to use this code snippet in your own projects.
You can use bind to solve this.
Create a helper function that will start animation for given canvas:
function animateCircle(canvas) {
var scope = {
ctx: canvas.getContext('2d')
// other properties, like currentPercent, finalPercent, etc
};
scope.interval = setInterval(circle.bind(scope), 20);
}
Change your circle function to refer variables from this instead of global ones:
function circle() {
// your old code with corresponding changes
// e.g.
var ctx = this.ctx; // references corresponding scope.ctx
// or
this.currentPercent++; // references corresponding scope.currentPercent
}
Working JSFiddle, if something is not clear.
I have a black canvas with things being drawn inside it. I want the things drawn inside to fade to black, over time, in the order at which they are drawn (FIFO). This works if I use a canvas which hasn't been resized. When the canvas is resized, the elements fade to an off-white.
Question: Why don't the white specks fade completely to black when the canvas has been resized? How can I get them to fade to black in the same way that they do when I haven't resized the canvas?
Here's some code which demonstrates. http://jsfiddle.net/6VvbQ/35/
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.fillRect(0, 0, 300, 150);
// Comment this out and it works as intended, why?
canvas.width = canvas.height = 300;
window.draw = function () {
context.fillStyle = 'rgba(255,255,255,1)';
context.fillRect(
Math.floor(Math.random() * 300),
Math.floor(Math.random() * 150),
2, 2);
context.fillStyle = 'rgba(0,0,0,.02)';
context.fillRect(0, 0, 300, 150);
setTimeout('draw()', 1000 / 20);
}
setTimeout('draw()', 1000 / 20);
The problem is two-parted:
There is a (rather known) rounding error when you draw with low alpha value. The browser will never be able to get the resulting mix of the color and alpha channel equal to 0 as the resulting float value that is mixed will be converted to integer at the time of drawing which means the value will never become lower than 1. Next time it mixes it (value 1, as alpha internally is a value between 0 and 255) will use this value again and it get rounded to again to 1, and forever it goes.
Why it works when you have a resized canvas - in this case it is because you are drawing only half the big canvas to the smaller which result in the pixels being interpolated. As the value is very low this means in this case the pixel will turn "black" (fully transparent) as the average between the surrounding pixels will result in the value being rounded to 0 - sort of the opposite than with #1.
To get around this you will manually have to clear the spec when it is expected to be black. This will involve tracking each particle/spec yourselves or change the alpha using direct pixel manipulation.
Update:
The key is to use tracking. You can do this by creating each spec as a self-updating point which keeps track of alpha and clearing.
Online demo here
A simple spec object can look like this:
function Spec(ctx, speed) {
var me = this;
reset(); /// initialize object
this.update = function() {
ctx.clearRect(me.x, me.y, 1, 1); /// clear previous drawing
this.alpha -= speed; /// update alpha
if (this.alpha <= 0) reset(); /// if black then reset again
/// draw the spec
ctx.fillStyle = 'rgba(255,255,255,' + me.alpha + ')';
ctx.fillRect(me.x, me.y, 1, 1);
}
function reset() {
me.x = (ctx.canvas.width * Math.random())|0; /// random x rounded to int
me.y = (ctx.canvas.height * Math.random())|0; /// random y rounded to int
if (me.alpha) { /// reset alpha
me.alpha = 1.0; /// set to 1 if existed
} else {
me.alpha = Math.random(); /// use random if not
}
}
}
Rounding the x and y to integer values saves us a little when we need to clear the spec as we won't run into sub-pixels. Otherwise you would need to clear the area around the spec as well.
The next step then is to generate a number of points:
/// create 100 specs with random speed
var i = 100, specs = [];
while(i--) {
specs.push(new Spec(ctx, Math.random() * 0.015 + 0.005));
}
Instead of messing with FPS you simply use the speed which can be set individually per spec.
Now it's simply a matter of updating each object in a loop:
function loop() {
/// iterate each object
var i = specs.length - 1;
while(i--) {
specs[i].update(); /// update each object
}
requestAnimationFrame(loop); /// loop synced to monitor
}
As you can see performance is not an issue and there is no residue left. Hope this helps.
I don't know if i have undertand you well but looking at you fiddle i think that, for what you are looking for, you need to provide the size of the canvas in any iteration of the loop. If not then you are just taking the initial values:
EDIT
You can do it if you apply a threshold filter to the canvas. You can run the filter every second only just so the prefromanece is not hit so hard.
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.fillRect(0,0,300,150);
//context.globalAlpha=1;
//context.globalCompositeOperation = "source-over";
var canvas2 = document.getElementById('canvas2');
var context2 = canvas2.getContext('2d');
canvas2.width=canvas2.height=canvas.width;
window.draw = function(){
var W = canvas2.width;
var H = canvas2.height;
context2.fillStyle='rgba(255,255,255,1)';
context2.fillRect(
Math.floor(Math.random()*W),
Math.floor(Math.random()*H),
2,2);
context2.fillStyle='rgba(0,0,0,.02)';
context2.fillRect(0,0,W,H);
context.fillStyle='rgba(0,0,0,1)';
context.fillRect(0,0,300,150);
context.drawImage(canvas2,0,0,300,150);
setTimeout('draw()', 1000/20);
}
setTimeout('draw()', 1000/20);
window.thresholdFilter = function () {
var W = canvas2.width;
var H = canvas2.height;
var i, j, threshold = 30, rgb = []
, imgData=context2.getImageData(0,0,W,H), Npixels = imgData.data.length;
for (i = 0; i < Npixels; i += 4) {
rgb[0] = imgData.data[i];
rgb[1] = imgData.data[i+1];
rgb[2] = imgData.data[i+2];
if ( rgb[0] < threshold &&
rgb[1] < threshold &&
rgb[2] < threshold
) {
imgData.data[i] = 0;
imgData.data[i+1] = 0;
imgData.data[i+2] = 0;
}
}
context2.putImageData(imgData,0,0);
};
setInterval("thresholdFilter()", 1000);
Here is the fiddle: http://jsfiddle.net/siliconball/2VaLb/4/
To avoid the rounding problem you could extract the fade effect to a separate function with its own timer, using longer refresh interval and larger alpha value.
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.fillRect(0, 0, 300, 150);
// Comment this out and it works as intended, why?
canvas.width = canvas.height = 300;
window.draw = function () {
context.fillStyle = 'rgba(255,255,255,1)';
context.fillRect(
Math.floor(Math.random() * 300),
Math.floor(Math.random() * 300),
2, 2);
setTimeout('draw()', 1000 / 20);
}
window.fadeToBlack = function () {
context.fillStyle = 'rgba(0,0,0,.1)';
context.fillRect(0, 0, 300, 300);
setTimeout('fadeToBlack()', 1000 / 4);
}
draw();
fadeToBlack();
Fiddle demonstrating this: http://jsfiddle.net/6VvbQ/37/
I'm drawing simple text in HTML5 canvas using this:
context.fillStyle = "#FF0000"
context.font = "italic 20pt Arial";
context.fillText("sfddsfs", 50, 50);
Now I want to animate fade out of this text. How can that be done?
Edit: I'm aware there's currently no ready to use way to do this (at least I can't find anything). I'm a noob in graphic programming but want to learn, so any hint about where to start is appreciated.
Maybe something like putting the text in an own canvas and changing globalAlpha of the canvas...? But the background of the canvas would have to be transparent. And don't know about performance, have a lot of small labels appearing and dissapearing everywhere which need to be faded out.
It's easier if you use rgba() notation to set the fillStyle rather than the hexadecimal notation. Here's a working example (demo):
// Create a canvas element and append it to <body>
var canvas = document.createElement('canvas'),
context = canvas.getContext('2d');
document.body.appendChild(canvas);
function fadeOut(text) {
var alpha = 1.0, // full opacity
interval = setInterval(function () {
canvas.width = canvas.width; // Clears the canvas
context.fillStyle = "rgba(255, 0, 0, " + alpha + ")";
context.font = "italic 20pt Arial";
context.fillText(text, 50, 50);
alpha = alpha - 0.05; // decrease opacity (fade out)
if (alpha < 0) {
canvas.width = canvas.width;
clearInterval(interval);
}
}, 50);
}
fadeOut('sfddsfs');
I think I got it. Forgot to mention that I have already a render loop and text objects which draw themselves on the canvas each frame.
So the solution is to add alpha variable to the text objects:
this.alpha = 1;
and each x frames or time reduce this a bit.
and in the render loop:
context.globalAlpha = textObject.alpha;
//draw the text
context.globalAlpha = 1;
There is no built-in solution to this. You have to do the animation(fade) by drawing each frame individually:
Set up some timing function that calculates the gradient between #FF0000 and the background color and redraws the text over and over until the background color is reached.
I'm dabbling with html5 and javascript (I know nothing of both). I found an example of some html5, copied it, and started experimenting. Heres some code. The idea is that when any key is pressed, two squares start moving left (doesn't clean up behind it yet). What I don't understand is why I cant change colour (Ive indicated below). Any ideas? Im obviously doing something very wrong.
<!doctype html>
<!-- this source copied from http://www.xanthir.com/blog/b48B0 -->
<canvas width=800 height=800>
</canvas>
<script>
var canvas = document.getElementsByTagName("canvas")[0];
var context = canvas.getContext('2d');
var x = 230;
var y = 380;
// First, we'll paint the whole canvas black.
context.fillStyle = "black";
context.fillRect(0,0,800,800);
context.fillStyle = "red";
context.fillRect(0,0,30,30);
context.fillRect(0,100,30,30);
context.fillStyle = "green";
context.fillRect(0,200,30,30);
// Now we'll draw some shapes
// circle
context.fillStyle = "#06c";
context.strokeStyle = "white";
// These can be any CSS color.
context.lineWidth = 3;
context.beginPath();
context.moveTo(450,250);
context.arc(375,250,75,0,2*Math.PI,false)
context.closePath();
context.fill();
context.stroke();
// A triangle! And a rainbow!
context.beginPath();
context.moveTo(150,50);
context.lineTo(90,150);
context.lineTo(210,150);
context.lineTo(150,50);
context.closePath();
var rainbow = context.createLinearGradient(150,50,150,150);
rainbow.addColorStop(.1,"red");
rainbow.addColorStop(.3,"orange");
rainbow.addColorStop(.5,"yellow");
rainbow.addColorStop(.7,"lime");
rainbow.addColorStop(.9,"blue");
context.fillStyle = rainbow;
context.fill();
// Some text! And a shadow!
context.shadowOffsetX = -2;
context.shadowOffsetY = 2;
context.shadowColor = "#f88";
context.shadowBlur = .01;
context.fillStyle = "red";
context.font = "bold 72px monospace";
context.fillText("Foo Bar",30,400);
context.fillStyle = "blue";
context.fillRect(0,300,30,30);
// ???????????? end of main. The current context now seems to remain (blue fillstyle with some shadow )
// routine here : press any key to animate two new blocks over writing ----------------
document.onkeydown = function(e) {
context.fillstyle = "red"; // <-- ???????? this doesnt work (remains same colour as last one in main )
context.fillRect(x,y,50,50); // <-- ???????? draws a square in blue, not red
x = x - 5;
context.fillstyle = "white"; // <-- ???????? this doesnt work (remains same colour as last one in main )
context.fillRect(x -100,y ,50,50); // <-- ???????? draws a square in blue, not white
}
Because you wrote fillstyle and not fillStyle. You need to capitalize the S.
It is valid in Javascript because you are just attaching a new fillstyle field (which does not exist and is meaningless) to that context.
So you gotta be careful. Typos can cause lots of trouble, because the resulting code isn't technically an error, but its certainly not what you want!