draw donut path using canvas element - javascript

I want to draw a dounut path using canvas. It contains the inner and outer arch connecting with line. But I am getting wrongly canvas image. Please see the below image.
Expected:
This is my code.
this.ctx.beginPath();
this.ctx.moveTo(options.x, options.y);
this.ctx.arc(options.x, options.y, options.radius, options.start, options.end, false);
this.ctx.lineTo(options.x, options.y);
this.ctx.arc(options.x, options.y, options.innerR, options.start, options.end, false);
this.ctx.closePath();
Anyone please help me to solve this issue.
Thanks,
Bharathi.

When moving your "pen" to (options.x, options.y) and then drawing a circle around this point, your "pen" first has to go to the starting position of your arc. Here the line is drawn that you don't want to have on your canvas.
To solve this problem, you have to calculate the starting position of your outer circle (depending on the start angle). You should try with sin or cos to calculate your "new" x and y.
It would then look something like
var newX = options.x + options.radius * cos(options.start);
var newY = options.y + options.radius * sin(options.start);
Then move to this position
this.ctx.moveTo(newX, newY);
And draw the circle around the old x and y
this.ctx.arc(options.x, options.y, options.radius, options.start, options.end, false);
For the inner circle and the end positions you can calculate it similar to this.

I have done it using css
var gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
gradient.addColorStop(0, "#008B8B");
gradient.addColorStop(0.75, "#F5DEB3");
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
Just remove the last two lines from my above code you will see that the inner circle appears again
SEE DEMO HERE

Related

Transparent circles not showing up [HTML5/JavaScript]

I'm trying to draw fireflies on a canvas. I have a image of a 1x1 white pixel and I want to have a transparent circle surrounding it to simulate a glow. So far, I've managed to draw the circle, but when I try to change the global alpha of my 2d context, the image doesn't draw and neither does the circle. This has been confusing me for a while because I draw the image before I draw its surrounding circle. How can I go about fixing this?
My code:
thatBug.draw = function () {
ctx.drawImage(bugImage, thatBug.x, thatBug.y, thatBug.size, thatBug.size);
ctx.save();
ctx.globalAlpha(0.4);
ctx.beginPath();
ctx.arc(thatBug.x, thatBug.y, thatBug.size + thatBug.glowAmt, 0, 2 * Math.PI, false);
ctx.fillStyle = 'white';
ctx.fill();
ctx.restore();
};
Fixed it myself. ctx.globalAlpha(0.4) should be globalAlpha = 0.4

animating a rotated image in canvas

hey guys i have a function that strokes a line based on the angle received from the user and also moves an image using some basic maths. the only problem is i am unable to rotate image based on that angle as if i put this inside animation frame loop it doesn't work .please help
function move()
{
var theCanvas=document.getElementById("canvas1");
var context=theCanvas.getContext("2d");
context.clearRect(0, 0, theCanvas.width, theCanvas.height );
// context.fillStyle = "#EEEEEE";
//context.fillRect(0, 0,theCanvas.width, theCanvas.height );
context.beginPath();
context.setLineDash([3,2]);
context.lineWidth=10;
context.strokeStyle="black";
context.moveTo(x1,y1);
context.lineTo(x2,y2);
context.stroke();
context.drawImage(srcImg,x1+x_fact,y1-100+y_fact);
x_fact=x_fact+0.5;
y_fact=m*x_fact+c;
requestAnimationFrame(move);
}
move();
now please suggest me a way to rotate the image on the angle input only once so it can face according to the path and move in it.
thank you in advance.
If you want to rotate the image by its corner use something like this:
... your other code here ...
var x = x1+x_fact, // for simplicity
y = y1-100+y_fact;
context.save(); // save state
context.translate(x, y); // translate to origin of rotation
context.rotate(angle); // rotate, provide angle in radians
context.drawImage(srcImg, 0, 0); // as we are translated we draw at [0,0]
context.restore(); // restore state removing transforms
If you want to rotate it by center simply translate, rotate and then translate back 50% of the image's width and height.
save/restore are relative expensive operations - you can simply reset transformation all together after each draw if you don't need transformations elsewhere:
context.setTransform(1, 0, 0, 1, 0, 0); // instead of restore(), remove save()

Multiple light sources on canvas

I want to place a number of light sources on a background for a game I'm making, which works great with one light source as shown below:
This is achieved by placing a .png image above everything else that becomes more transperant towards the center, like this:
Works great for one light source, but I need another approach where I can add more and move the light sources around.
I have considered drawing a similar "shadow layer" pixel by pixel for each frame, and calculate the transparency depending of the distance to each light source. However, that would probably be very slow and I'm sure there are way better solutions to this problem.
The images are just examples and each frame will have considerably more content to move around and update using requestAnimationFrame.
Is there a light weight and simple way to achieve this? Thanks in advance!
Edit
With the help of ViliusL, I came up with this masking solution:
http://jsfiddle.net/CuC5w/1/
// Create canvas
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = 300;
canvas.height = 300;
document.body.appendChild(canvas);
// Draw background
var img=document.getElementById("cat");
ctx.drawImage(img,0,0);
// Create shadow canvas
var shadowCanvas = document.createElement('canvas');
var shadowCtx = shadowCanvas.getContext('2d');
shadowCanvas.width = canvas.width;
shadowCanvas.height = canvas.height;
document.body.appendChild(shadowCanvas);
// Make it black
shadowCtx.fillStyle= '#000';
shadowCtx.fillRect(0,0,canvas.width,canvas.height);
// Turn canvas into mask
shadowCtx.globalCompositeOperation = "destination-out";
// RadialGradient as light source #1
gradient = shadowCtx.createRadialGradient(80, 150, 0, 80, 150, 50);
gradient.addColorStop(0, "rgba(255, 255, 255, 1.0)");
gradient.addColorStop(1, "rgba(255, 255, 255, .1)");
shadowCtx.fillStyle = gradient;
shadowCtx.fillRect(0, 0, canvas.width, canvas.height);
// RadialGradient as light source #2
gradient = shadowCtx.createRadialGradient(220, 150, 0, 220, 150, 50);
gradient.addColorStop(0, "rgba(255, 255, 255, 1.0)");
gradient.addColorStop(1, "rgba(255, 255, 255, .1)");
shadowCtx.fillStyle = gradient;
shadowCtx.fillRect(0, 0, canvas.width, canvas.height);
Another way to play with light is to use the globalCompositeOperation mode 'ligther' to ligthen things, and just use globalAlpha to darken things.
First here's an image, with a cartoon lightening on the left, and a more realistic lightening on the right, but you'd rather watch the fiddle, since it's animated :
http://jsfiddle.net/gamealchemist/ABfVj/
So how i did things :
To darken :
- Choose a darkening color( most likely black, but you can choose a red or another color to teint the result).
- choose an opacity ( 0.3 seems a good start value ).
- fillRect the area you want to darken.
function darken(x, y, w, h, darkenColor, amount) {
ctx.fillStyle = darkenColor;
ctx.globalAlpha = amount;
ctx.fillRect(x, y, w, h);
ctx.globalAlpha = 1;
}
To lighten :
- Choose a lightening color. Beware that this color's r,g,b will be added to the previous point's r,g,b : if you use a high value your color will get burnt.
- change the globalCompositeOperation to 'lighter'
- you might change opacity also, to have more control over the lightening.
- fillRect or arc the area you want to lighten.
If you draw several circles while in lighter mode, the results will add up, so you can choose a quite low value and draw several circles.
function ligthen(x, y, radius, color) {
ctx.save();
var rnd = 0.03 * Math.sin(1.1 * Date.now() / 1000);
radius = radius * (1 + rnd);
ctx.globalCompositeOperation = 'lighter';
ctx.fillStyle = '#0B0B00';
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * π);
ctx.fill();
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(x, y, radius * 0.90+rnd, 0, 2 * π);
ctx.fill();
ctx.beginPath();
ctx.arc(x, y, radius * 0.4+rnd, 0, 2 * π);
ctx.fill();
ctx.restore();
}
Notice that i added a sinusoidal variation to make the light more living.
Ligthen : another way :
You can also, while still using the 'ligther' mode, use a gradient to have a smoother effect (first one is more cartoon like, unless you draw a lot of circles.).
function ligthenGradient(x, y, radius) {
ctx.save();
ctx.globalCompositeOperation = 'lighter';
var rnd = 0.05 * Math.sin(1.1 * Date.now() / 1000);
radius = radius * (1 + rnd);
var radialGradient = ctx.createRadialGradient(x, y, 0, x, y, radius);
radialGradient.addColorStop(0.0, '#BB9');
radialGradient.addColorStop(0.2 + rnd, '#AA8');
radialGradient.addColorStop(0.7 + rnd, '#330');
radialGradient.addColorStop(0.90, '#110');
radialGradient.addColorStop(1, '#000');
ctx.fillStyle = radialGradient;
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * π);
ctx.fill();
ctx.restore();
}
i also added here a sin variation.
Rq : creating a gradient on each draw will create garbage : store the gradient if you use a single gradient, and store them in an array if you want to animate the gradients.
If you are using the same light in several places, have a single gradient built, centered on (0,0), and translate the canvas before drawing always with this single gradient.
Rq 2 : you can use clipping to prevent some parts of the screen to be lightened (if there's an obstacle).
I added the blue circle on my example to show this.
So you might want to ligthen directly your scene with those effects, or create separately a light layer that you darken/lighten as you want before drawImage it on the screen.
There are too many scenari to discuss them here (light animated or not, clipping or not, pre-compute a light layer or not, ...) but as far as speed is concerned, for Safari and iOS safari, the solution using rect/arc draws -either with gradient or a solid fill- will be rocket faster than drawing an image/canvas.
On Chrome it will be quite the opposite : it's faster to draw an image than to draw each geometry when the geometry count raises.
Firefox is rather similar to Chrome for this.
your png should have full transparent corners and not transparent white in middle.
or you can draw this, but not pixel by pixel like here jsfiddle.net/pr9r7/2/
More examples: jsfiddle.net/pr9r7/3/ http://codepen.io/cwolves/pen/prvnb
Here is my Take on it:
A. Don't worry about performance until you have tried it out. The Canvas is pretty darn fast at drawing.
B. Rather than having a image with dark Corners and a Transparent middle. Why don't you try and make it more "IRL" and have the overall world be more Dark and let the light-source illuminate the Area? Highlight a small area, instead of darken everything EXCEPT a small Area.

HTML5: Antialiasing leaves traces when I erase the image

I want to move a widget around on the canvas, and for various reasons I don't want to use sprites. I'm using the latest version of Chrome. In order to move the widget, I 'undraw' it and then redraw it in another place. By 'undraw', I mean that I just draw the same image in the same place, but draw it with the same color as the background, so the widget disappears completely before I draw the new one. The problem is that when I 'undraw', traces of the original image remain on the canvas. I've poked around on related questions here and haven't found anything that helps. I understand the problem of drawing a one-pixel line and getting anti-aliasing, so I set my line width to 2 (and various other non-integer values), but to no avail. Anyone have any ideas? Here's a fiddle demo, and here's the function that does the update:
function draw(){
if(previousX !== null) {
ctx.lineWidth = 1;
ctx.fillStyle = '#ffffff';
ctx.strokeStyle = '#ffffff';
drawCircle(previousX, previousY, 20);
}
ctx.lineWidth = 1;
ctx.fillStyle = '#000000';
ctx.strokeStyle = '#000000';
drawCircle(x, y, 20);
console.log('drew circle (' + x + ', ' + y + ')');
previousX = x;
previousY = y;
}
P.S. I'm just a hobbyist with no great experience in graphics, so please dumb-down your answer a bit if possible.
When your draw a shape with anti-aliasing, you are doing a solid covering of some pixels, but only a partial covering of the edge pixels. The trouble is that pixels (temporarily ignoring LCD panels) are indivisible units. So how do we partially cover pixels? We achieve this using the alpha channel.
The alpha channel (and alpha blending) combines the colour at the edge of a circle with the colour underneath it. This happens when the circle only partially covers the pixel. Here's a quick diagram to visualise this issue.
The mixing of colours causes a permanent change that is not undone by drawing the circle again in the background colour. The reason: colour mixing happens again, but that just causes the effect to soften.
In short, redrawing only covers up the pixels with total coverage. The edge pixels are not completely part of the circle, so you cannot cover up the edge effects.
If you need to erase the circle, rather think about it in terms of restoring what was originally there. You can probably copy the original content, then draw the circle, then when you want to move the circle, restore the original content and repeat the process.
This previous SO question may give you some ideas about copying canvas regions. It uses the drawImage method. The best solution would combine the getImageData and putImageData methods. I have modified your Fiddle example to show you how you might do this. You could try the following code:
var x, y, vx, vy;
var previousX = null, previousY = null;
var data = null;
function draw(){
ctx.lineWidth = 2.5;
ctx.fillStyle = '#000000';
ctx.strokeStyle = '#FF0000';
drawCircle(x, y, 20);
previousX = x;
previousY = y;
}
function drawCircle(x, y, r){
// Step 3: Replace the stuff that was underneath the previous circle
if (data != null)
{
ctx.putImageData(data, previousX - r-5, previousY - r-5);
}
// Step 1: Copy the region in which we intend to draw a circle
data = ctx.getImageData(x - r-5, y - r-5, 2 * r + 10, 2 * r + 10);
// Step 2: Draw the circle
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.closePath();
ctx.stroke();
ctx.fill();
}

html5 canvas stroke color always displaying as grey?

I've got an array like this:
var hitColors = ["#ff0000","#00ff00","#0000ff","#ffff00","#00ffff","#ff00ff"];
I've got a canvas that I'm "redrawing" every few seconds like this:
// main canvas rectangle
context.beginPath();
context.rect(0, 0, canvasWidth, canvasHeight);
context.fillStyle = '#FFFFFF';
context.fillRect(0, 0, canvasWidth, canvasHeight);
context.rect(thisXPos-1, thisYPos-1, words[activeWord][2].width+2, words[activeWord][2].height+2);
context.strokeStyle = hitColors[hitSpot];
alert('"' + hitColors[hitSpot] + '"');
alert(context.strokeStyle);
context.lineWidth = 1;
context.stroke();
context.closePath();
I can confirm that context.closePath(); is returning the proper color from the array but when I alert context.StrokeStyle it's always set to #000000 and the rect border is grey. How can I fix this?
Add or subtract 0.5 pixels from your values.
Basically, if you try to draw a 1px line centered around an integer pixel value what you end up with is a 2 pixel line centered around that point which and the line will be semi-transparent. Semi-transparent black looks like grey. So, if you want a straight line of any colour that is exactly 1 pixel wide, you need to draw that line with at pixel intervals of 0.5.
I switched the array to this:
var hitColors = ["#f00","#0f0","#00f","#ff0","#0ff","#f0f"];
and it started working properly.
You never set you strokeStyle. its defaulting to #000000.

Categories

Resources