Using Clip in canvas causing Pixels - javascript

I am trying to using context.clip() to clip a draw arc from other one and fill the clipped result.
But when i clip section & fill it, it gives pixelated fill .
var ctx = document.getElementById("canvas").getContext("2d");
var x = 150 ;
var y = 150 ;
var r = 100 ;
ctx.save() ;
ctx.translate(x,y) ;
ctx.beginPath() ;
ctx.arc(0,0,r,0,2*Math.PI);
ctx.closePath() ;
ctx.fillStyle = "cyan" ;
ctx.fill() ;
ctx.lineWidth = 10;
ctx.stroke();
ctx.restore() ;
ctx.save() ;
ctx.clip() ;
ctx.translate(x,y);
ctx.beginPath();
ctx.moveTo(r,-r-10);
ctx.arc(0,-r-10,r,0,Math.PI*2);
ctx.closePath();
ctx.fillStyle = "#f2f2f2";
ctx.fill();
ctx.lineWidth = 1;
ctx.stroke();
ctx.restore();
https://jsfiddle.net/x0d0n40z/1/

An alternative approach which eliminates the need for clip()/save()/restore() is to use a few steps of compositing.
Clipping mask is anti-aliased in some browsers while in other not. To obtain consistency (and in some cases also performance since save-clip-restore are relative expensive operations) using composition is preferred if possible.
In this case:
Fill main arc in target color
Define a clipping arc
Change composite mode to destination-out and fill (will cut main)
Change composite mode to source-atop and stroke (will outline cut)
Change composite mode to source-over and stroke outline of main circle
Example
Update: Simplified steps (with the last step merged into the process, ref. comments). I also chose to demonstrate use of the Path2D since we can reuse the object without interfering with the path on the ordinary context -
var ctx = c.getContext("2d"),
p = new Path2D(), // this will store main shape for reuse
x = 75, y = 75, radius = 70;
// main arc
p.arc(x, y, radius, 0, 6.28); // store to path object
ctx.fillStyle = "cyan";
ctx.fill(p); // fill path object
// clip top arc
ctx.globalCompositeOperation = "source-atop";
ctx.arc(x, y - radius, radius, 0, 6.28);
ctx.fillStyle = "#09f";
ctx.fill();
ctx.lineWidth = 5;
ctx.stroke();
// stroke main arc
ctx.globalCompositeOperation = "source-over";
ctx.stroke(p); // stroke path object
body {background:#e9e9e9}
<canvas id=c></canvas>
Old version:
var ctx = c.getContext("2d"),
x = 75, y = 75, radius = 70;
// main arc
ctx.arc(x, y, radius, 0, 6.28);
ctx.fillStyle = "cyan";
ctx.fill();
// clipping arc
ctx.beginPath();
ctx.arc(x, y - radius, radius, 0, 6.28);
// cut step
ctx.globalCompositeOperation = "destination-out";
ctx.fill();
// stroke gap step
ctx.globalCompositeOperation = "source-atop";
ctx.lineWidth = 10;
ctx.stroke();
// stroke whole outline
ctx.globalCompositeOperation = "source-over";
ctx.beginPath();
ctx.arc(x, y, radius, 0, 6.28);
ctx.lineWidth = 5;
ctx.stroke();
// if you want to color the clip then use this:
ctx.globalCompositeOperation = "destination-atop";
ctx.fillStyle = "#09f";
ctx.fill();
body {background:#e9e9e9}
<canvas id=c></canvas>

The problem is that the clip boundary is not being anti alised.
To solve you can render the shape without using the clip. The ctx.arc method lets you set the start and end angles so you can get the inset by filling two arcs.
You will need to get the angles where the clip circle and the inset circle intercept.
For this case it is very simple. First get the distance between the circles, and the angle from one to the other. This works only for two circles of same radius.
var c = {x:?,y:?}; // circle one location
var c1 = {x:?,y:?}; // circle two location
var radius = ?; // radius of both
var angle = Math.atan2(c1.y - c.y, c1.x - c.x); // get the angle from one to the next
var dist = Math.hypot(c1.x - c.x, c1.y - c.y); // get the distance. NOTE IE does not have hypot so do it the normal way with Math.sqrt....
Now you have the angle and distance the intercepts are a simple relationship between the distance and the radius
var iAngle = Math.acos(dist / 2 / radius); // the angle from the line between the circles
// to the intercepts
Now you have that angle you can draw the two arcs
ctx.beginPath();
ctx.arc(c.x,c.y,radius,angle - iAngle , angle + iAngle); // first arc
ctx.arc(c1.x,c1.y, radius, angle + Math.PI - iAngle, angle + Math.PI + iAngle); // second arc
ctx.fill();
ctx.stroke();
There is not much you can do to prevent the jaggies from effecting the clip area. Another way to achieve clipping is to use ctx.globalCompositeOperation to render a mask. You can mask in and out, and many more options. This will be a better solution when the clipping area becomes more complex.

I finally figured the right way to correct the bug .
Heres the clean result of what i wanted https://jsfiddle.net/x0d0n40z/6/
Code :
var ctx = document.getElementById("canvas").getContext("2d");
var r = 50
x = ctx.canvas.width/2;
y = ctx.canvas.height/2;
var offset = 60;
ctx.save();
ctx.setTransform(1,0,0,1.5,x,y);
ctx.beginPath();
ctx.arc(0,0,r,0,2*Math.PI);
ctx.stroke();
ctx.clip();
ctx.beginPath();
ctx.arc(0,0,r,0,2*Math.PI,false);
ctx.fillStyle = "cyan";
ctx.fill();
ctx.setTransform(1, 0, 0, 1, x, y);
ctx.beginPath();
ctx.arc(0,-offset,r,0,2*Math.PI,false);
ctx.fillStyle = "#f2f2f2";
ctx.fill();
ctx.lineWidth = 1 ;
ctx.stroke();
ctx.setTransform(1,0,0,1.5,x,y);
ctx.beginPath();
ctx.arc(0,0,r,0,2*Math.PI,false);
ctx.lineWidth = 3 ;
ctx.stroke();
ctx.restore();
Source from were i learned to use clip : http://www.html5canvastutorials.com/advanced/html5-canvas-clipping-region-tutorial/

Related

Gradients at each vertex of a triangle with HTML5 canvas

How can I fill a triangle with gradients starting at its vertices given a color for each vertex?
I'm trying to reproduce something like this:
I'm making use of the built in fill function from the HTML5 canvas Context2D. I'm trying to avoid having to deal with pixel-by-pixel interpolations based on their distance to the vertices. I fear it wont be as performatic as the built-in fill function (?). Also I can't deal with WebGL right now.
I've done a trick using radial gradients, but, there are a few problems with my naive approach:
The colors don't seem to blend well
The last applied gradient overwrites the others
The value used in the radius variable is arbitrary
OBS: I don't know if it's relevant but, I'm building a triangle strip (indexed geometry actually).
var canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");
var v1 = { x: 100, y: 0 };
var v2 = { x: 0, y: 180 };
var v3 = { x: 200, y: 180 };
var radius = 175;
var grd1 = ctx.createRadialGradient(v1.x, v1.y, 0, v1.x, v1.y, radius);
grd1.addColorStop(0, "#FF0000FF");
grd1.addColorStop(1, "#FF000000");
var grd2 = ctx.createRadialGradient(v2.x, v2.y, 0, v2.x, v2.y, radius);
grd2.addColorStop(0, "#00FF00FF");
grd2.addColorStop(1, "#00FF0000");
var grd3 = ctx.createRadialGradient(v3.x, v3.y, 0, v3.x, v3.y, radius);
grd3.addColorStop(0, "#0000FFFF");
grd3.addColorStop(1, "#0000FF00");
ctx.beginPath();
ctx.moveTo(v1.x, v1.y);
ctx.lineTo(v2.x, v2.y);
ctx.lineTo(v3.x, v3.y);
ctx.closePath();
ctx.fillStyle = "#FFFFFFFF"; // fill with white and apply the gradients on top of it
ctx.fill();
ctx.fillStyle = grd1;
ctx.fill();
ctx.fillStyle = grd2;
ctx.fill();
ctx.fillStyle = grd3;
ctx.fill();
<canvas width="200" height="180"></canvas>
The colors don't seem to blend well
For this you can use the globalCompositeOperation property of your 2D context to one of its blend modes, even though in your case the compositing mode "lighter" with a black background seems to produce the closest result to your model.
The last applied gradient overwrites the others
Thanks to the previous bullet point, it's not the case anymore.
The value used in the radius variable is arbitrary
Doesn't look like so to me, it does correspond to the distance between every points of your equilateral triangle and its center, which makes perfect sense.
var canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");
// reordered to make the same as OP's image
var v1 = { x: 0, y: 180 };
var v2 = { x: 200, y: 180 };
var v3 = { x: 100, y: 0 };
var radius = 180;
var grd1 = ctx.createRadialGradient(v1.x, v1.y, 0, v1.x, v1.y, radius);
grd1.addColorStop(0, "#FF0000FF");
grd1.addColorStop(1, "#FF000000");
var grd2 = ctx.createRadialGradient(v2.x, v2.y, 0, v2.x, v2.y, radius);
grd2.addColorStop(0, "#00FF00FF");
grd2.addColorStop(1, "#00FF0000");
var grd3 = ctx.createRadialGradient(v3.x, v3.y, 0, v3.x, v3.y, radius);
grd3.addColorStop(0, "#0000FFFF");
grd3.addColorStop(1, "#0000FF00");
ctx.beginPath();
ctx.moveTo(v1.x, v1.y);
ctx.lineTo(v2.x, v2.y);
ctx.lineTo(v3.x, v3.y);
ctx.closePath();
// fill with black
ctx.fill();
// set blend mode
ctx.globalCompositeOperation = "lighter";
ctx.fillStyle = grd1;
ctx.fill();
ctx.fillStyle = grd2;
ctx.fill();
ctx.fillStyle = grd3;
ctx.fill();
// if you need to draw something else, don't forget to reset the gCO
ctx.globalCompositeOperation = "source-over";
<canvas width="200" height="180"></canvas>

Create a cone with shadows

I would like to create a circle with a special shadow effect.
Like this one:
.
It should look like a cone in wood or metal.
I tried to do something with the radial gradiant in canvas but i can't creat that special Effekt.
I donĀ“t know how to create the this shadow effect.
Can somebody give me a tip or help me?
This is what I've tried: JSFiddle
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 100,
y = 75,
innerRadius = 1,
outerRadius = 70,
radius = 60;
ctx.arc(x, y, radius, 0, 2 * Math.PI);
var gradient = ctx.createRadialGradient(x, y, innerRadius, x, y, outerRadius);
gradient.addColorStop(0, '#FF9900');
gradient.addColorStop(1, '#FFFFFF');
ctx.fillStyle = gradient;
ctx.fill();
Greetings from Germany
Matzuman
There is unfortunately no gradient type in canvas which allow you to specify a radiant gradient. You have to provide a mechanism to do so manually.
You could use a shadow approach drawing the object off-screen while offsetting the shadow so it overlapped the cone base. One for light and one for dark side.
You can achieve a better effect though by drawing a "light/dark stripe" rotated around the center at varying opacity levels depending on angle.
Example "rendering" the cone
This example allow you to adjust parameters like how visible the reflections should be, what colors, size of cone etc. Experiment with the values to find what you're after.
To offset the "light source", just rotate one time initially with the angle you need before rendering the overlapping stripes.
var ctx = document.querySelector("canvas").getContext("2d"),
cx = 75, cy = 75, radius = 70, // for arc/cone
maxOpacity = 1, // max opacity (will accumulate)
angleStep = 0.01, // "resolution"
angle = 0, t; // current angle and opacity
// draw base of cone
ctx.fillStyle = "rgb(139, 108, 33)";
ctx.arc(cx, cy, radius, 0, 2*Math.PI);
ctx.fill();
// now rotate around center drawing a white stripe at varying opacity
// depending on angle
ctx.fillStyle = "rgb(181, 159, 109)";
ctx.translate(cx, cy); // pivot for rotation = center of cone
// half of the cone is done with white overlay
for(angle = 0; angle < Math.PI; angle += angleStep) {
// calculate t [0,1] based on angle. Multiply with max opacity
t = (angle < Math.PI * 0.5 ? angle : Math.PI - angle) / Math.PI * maxOpacity;
ctx.rotate(angleStep); // increase angle by step
ctx.globalAlpha = t; // set opacity to t
drawStripe(); // draw a small segment / "stripe"
}
// the other half of the cone is done with dark overlay
ctx.fillStyle = "rgb(95, 54, 5)";
for(angle = 0; angle < Math.PI; angle += angleStep) {
t = (angle < Math.PI * 0.5 ? angle : Math.PI - angle) / Math.PI * maxOpacity;;
ctx.rotate(angleStep);
ctx.globalAlpha = t;
drawStripe();
}
function drawStripe() {
ctx.beginPath();
ctx.lineTo(0, 0);
ctx.arc(0, 0, radius, 0, angleStep*5);
ctx.fill();
}
// top off by drawing a smaller circle on top
ctx.setTransform(1,0,0,1,0,0); // reset transforms
ctx.globalAlpha = 1; // reset alpha
ctx.fillStyle = "rgb(130, 97, 32)"; // draw in a topping
ctx.beginPath();
ctx.arc(cx, cy, radius * 0.25, 0, 2*Math.PI);
ctx.fill();
<canvas></canvas>
Example approximating a cone shape with shadows
var ctx = document.querySelector("canvas").getContext("2d"),
cx = 75, cy = 75, radius = 70, offset = radius * 2;
// draw base of cone
ctx.fillStyle = "rgb(139, 108, 33)";
ctx.arc(cx, cy, radius, 0, 2*Math.PI);
ctx.fill();
// offset next shape, couter-offset its shadow
ctx.translate(cx, offset*2); // make sure shape is drawn outside
ctx.scale(0.75, 1); // make shadow more narrow
ctx.globalCompositeOperation = "source-atop"; // comp. on top of existing pixels
ctx.shadowOffsetY = -offset * 1.1; // counter-offset shadow
ctx.shadowBlur = 25; // some blur
ctx.shadowColor = "rgba(181, 159, 109, 1)"; // highlight color
ctx.beginPath(); // draw new shape
ctx.arc(0, 0, radius * 0.6, 0, 2*Math.PI); // reduce radius ~50%
ctx.fill();
ctx.shadowOffsetY = -offset * 1.8; // counter-offset shadow
ctx.shadowColor = "rgba(95, 54, 5, 0.7)"; // shadow
ctx.beginPath(); // draw new shape
ctx.arc(0, 0, radius * 0.6, 0, 2*Math.PI); // reduce radius ~50%
ctx.fill();
// top off by drawing a smaller circle on top
ctx.setTransform(1,0,0,1,0,0); // reset transforms
ctx.globalCompositeOperation = "source-over"; // reset comp. mode
ctx.fillStyle = "rgb(130, 97, 32)"; // draw in a topping
ctx.beginPath();
ctx.arc(cx, cy, radius * 0.25, 0, 2*Math.PI);
ctx.fill();
<canvas></canvas>
Try using
ctx.shadowBlur = 40;
ctx.shadowColor = "#FF9900";
before drawing the circle.
shadowBlur sets the size of the shadow, you can set it to 0 if you want to disable it.
shadowColor is pretty self explanatory.

Create a radial gradient stroke around a circle

I want to create a radial gradient stroke around a circle,something similar to
Here is what I've tried so far,
var canvas = document.getElementById("analog-stopwatch");
var context = canvas.getContext('2d');
var cx=200, cy=200, radius=100;
context.beginPath();
context.arc(cx, cy, radius, 0, 2 * Math.PI, false);
// I want the ring width to be 20
var radialGradient = context.createRadialGradient(cx, cy, radius, cx, cy, radius+20);
radialGradient.addColorStop(0, "black");
radialGradient.addColorStop(1, "blue");
//context.lineWidth = 20;
context.strokeStyle = radialGradient;
context.stroke();
One way I could think of is creating a circle with radial gradient & clipping it with a concurrent circle of lesser radius, but is there any simpler way to achieve the same ?
There is a simpler way: draw the outer circle in one direction (ex:clockwise), then draw the inner circle with the other : it will be subtracted from the first path.
Then fill the resulting path :
fiddle :
http://jsbin.com/UCiCaYOn/1/edit?js,output
var canvas = document.getElementById("analog-stopwatch");
var context = canvas.getContext('2d');
var cx=200, cy=200, radius=100;
context.beginPath();
// !!!!
context.arc(cx, cy, radius+30, 0, 2 * Math.PI, false); // !!!
context.arc(cx, cy, radius, 0, 2 * Math.PI, true); // !!!
// !!!!
var radialGradient = context.createRadialGradient(cx, cy, radius, cx, cy, radius+20);
radialGradient.addColorStop(0, "black");
radialGradient.addColorStop(1, "blue");
context.fillStyle = radialGradient;
context.fill();
context.closePath();
Basically all you need to do is to change the rectangle a bit for the gradient and you're good (no need to stroke two arcs etc.):
var lineWidth = 20;
var radialGradient = context.createRadialGradient(cx, cy, radius-lineWidth*0.5,
cx, cy, radius+lineWidth*0.5);
Now you can stroke:
Updated fiddle here

html5 canvas stroke as clear line

i currently have the following:
ctx.save();
ctx.translate(459,258);
ctx.rotate(sec * Math.PI/36);
ctx.lineWidth = 10;
ctx.beginPath();
ctx.moveTo(135,0);
ctx.lineTo(210,0);
ctx.strokeStyle = 'rgba(0,153,255)';
ctx.stroke();
ctx.restore();
drawing a circle of lines (stroke). I want to convert it into a clearRect so that instead of drawing this circle of lines, i want it to erase a circle in the same shape... how can i do this?
i tried doing this but it did not work:
ctx.save();
ctx.translate(459,258);
ctx.rotate(sec * Math.PI/36);
ctx.lineWidth = 10;
ctx.beginPath();
ctx.moveTo(135,0);
ctx.lineTo(210,0);
ctx.clear();
ctx.restore();
thanks.

drawing Inscribe a Circle in a Triangle using a canvas

I am creating
"Inscribe a Circle in a Triangle using a canvas". But facing lots of problem. Well I tried to draw and Triangle in the middle of the canvas though its created i am wondering where to start drawing an circle which could be perfectly work for me.
With respective to mathematically I knew to draw circle, but when it comes to java script i am stuck.
kindly help me.
Thanks.
i have tried the following code to draw an traing at center of the canvas:-
var c=document.getElementById("myCanvas");
var context =c.getContext("2d");
check(ctx, 100, c.width/2, c.height/2);
function check(ctx, side, cx, cy){
var h = side * (Math.sqrt(3)/2);
ctx.strokeStyle = "black";
ctx.save();
ctx.translate(cx, cy);
ctx.beginPath();
ctx.moveTo(0,-h/2);
ctx.lineTo(-side/2, h / 2); // line a
ctx.lineTo(side /2, h / 2); // line b
ctx.lineTo(0,-h /2); // line c
ctx.stroke();
ctx.closePath();
ctx.save();
}
like this i want..
Ok check this .. Live Demo for equilateral triangle
Radius of circle inscribed in equilateral triangle = Sqrt(3)/6 * side
of triangle;
window.onload = function()
{
var c=document.getElementById("myCanvas");
var context =c.getContext("2d");
check(context,100,c.width/2,c.height/2);
circle(context,100,c.width/2,c.height/2);
}
function check(ctx, side, cx, cy){
var h = side * (Math.sqrt(3)/2);
ctx.strokeStyle = "black";
ctx.save();
ctx.translate(cx, cy);
ctx.beginPath();
ctx.moveTo(0,-h/2);
ctx.lineTo(-side/2, h / 2); // line a
ctx.lineTo(side /2, h / 2); // line b
ctx.lineTo(0,-h /2); // line c
ctx.stroke();
ctx.closePath();
ctx.restore();
}
function circle(ctx,side,cx,cy)
{
var h = side * (Math.sqrt(3)/2);
var radius = Math.sqrt(3)/6 * side; // Radius of the circle
cy = cy + h/2 - radius; // Center Y of circle
ctx.beginPath();
ctx.arc(cx,cy,radius,0,Math.PI * 2,false);
ctx.stroke();
ctx.closePath();
}
Check all formulas to find the radius of circle inscribed in different triangles here

Categories