Change the fill color in front direction - javascript

I am working on creating cylinder using canvas and I have coded for to fill the cylinder (animate) based on the percentage.
When I enter value in the textbox it start fill in back wards (Fill). But it has to fill (Green) in front direction direction how the top of the cylinder look like.
If we change the cy value can direction of fill will change. Any Suggestion / solution
Here is the Draw Cylinder code
function draw()
{
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
// draw grey main cylinder
drawCylinder(cx, cy, width, height, height / 8, '#b1b1b1', '#000');
// draw green progression cylinder
var currHeight = someValue * height / 100;
var newCenterY = cy - currHeight / 2 + height / 2;
//Here is where green fill starts
drawCylinder(cx, newCenterY, width, currHeight, height / 4, '#81ae45', null);
// draw (fill and stroke) the top of the progression cylinder
drawCylinderTop(cx, newCenterY, width, 100, height / 4, '#9a9a9a', null);
// stroke the top of the main cylinder
}
Here is my code for draw cylinder
function drawCylinder(x, y, w, h, vRadius, fillStyle, strokeStyle) {
var w2 = w / 2;
var h2 = h / 2;
var ytop = -h2;
var cpYtop = -h2 - vRadius;
var ybottom = h2;
var cpYbottom = h2 + vRadius;
ctx.save();
ctx.translate(x, y);
ctx.beginPath();
ctx.moveTo(-w2, ytop);
ctx.bezierCurveTo(-w2, cpYtop, w2, cpYtop, w2, ytop);
ctx.lineTo(w2, ybottom);
ctx.bezierCurveTo(w2, cpYbottom, -w2, cpYbottom, -w2, ybottom);
ctx.closePath();
performDraw(fillStyle);
ctx.restore();
}
If i try to change the bezierCurveTo in to static value still it was not changing.
I don't have reputation to put exact output image what I want.
Here is the updated fiddle link.
I have modified the below line of code
var newCenterY = cy + currHeight / 2 + height / 2;
Previously it was
var newCenterY = cy - currHeight / 2 + height / 2;
I am struggling to change the direction of fill color help needed.
Please do the needful.
Fiddle Link
Thanks in advance
M

I have added one more function two change the direction of filling
I have created one more function call drawCylinderprogress
function drawCylinderprogress(x, y, w, h, vRadius, fillStyle, strokeStyle) {
var w2 = w / 2;
var h2 = h / 2;
var ytop = -h2;
var cpYtop = -h2 - vRadius;
var ybottom = h2;
var cpYbottom = h2 + vRadius;
ctx.save();
ctx.translate(x, y);
ctx.beginPath();
ctx.moveTo(-w2, ytop);
ctx.bezierCurveTo(-w2, cpYtop/360, w2, cpYtop/360 , w2 , ytop);
ctx.lineTo(w2, ybottom);
ctx.bezierCurveTo(w2, cpYbottom, -w2, cpYbottom, -w2, ybottom);
ctx.closePath();
performDraw(fillStyle);
ctx.restore();
}
Regards
Mahadevan

Related

How to let the user draw an ellipse?

I'm making a simple paint program with javascript. The circle-tool is working as intended, but how do I add a tool for drawing an ellipse/oval?
I have reused much of the code for making the different tools (pencil, line, rectangle, and circle), and so far so good. But I can't get the code for drawing the ellipse right.
Here's the current and working code for drawing a circle filled with a random color:
var radius = Math.max(
Math.abs(ev._x - tool.x0),
Math.abs(ev._y - tool.y0)
) / 2;
var x = Math.min(ev._x, tool.x0) + radius;
var y = Math.min(ev._y, tool.y0) + radius;
context.fillStyle = 'hsl(' + 360 * Math.random() + ', 85%, 50%)';
context.beginPath();
context.arc(x, y, radius, 0, Math.PI*2, false);
context.stroke();
context.closePath();
context.fill();
I've tried to integrate it with the code already in use and the context.scale, but I don't get it right:
var radius = Math.max(
Math.abs(ev._x - tool.x0),
Math.abs(ev._y - tool.y0)
) / 2;
var radius2 = ;
var x = Math.min(ev._x, tool.x0) + radius;
var y = Math.min(ev._y, tool.y0) + radius;
context.save();
context.scale(1, radius2/radius);
context.beginPath();
context.arc(x, y, radius, 0, 2 * Math.PI);
context.restore();
context.lineWidth=2;
context.strokeStyle="#000";
context.stroke();
Is the var radius correct, and do I write the var radius2? The entire code is here JS Bin
The x attribute defines the x coordinate of the center of the ellipse
The y attribute defines the y coordinate of the center of the ellipse
The radiusX attribute defines the horizontal radius
The ry attribute defines the vertical radius
Image for your reference

Canvas speechbubble created in Javascript -> measureText height?

I'm currently trying to create a speechbubble for my canvas using javascript.
Problem 1:
I'm adding the width in the following way: ctx.measureText(text).width + 40 to make sure the width of the speechbubble is flexible and depends on the var text = 'Speechbubble test'; input. Also adding 40 pixels to add a margin left and right!
How could I get the height of the text to make it flexible also? I've been checking but couldn't find something similare to the measureText method and it doesn't seem to exist.
Is there any way to get the actual height of the text? I'm asking because I'm planning to add a line break to it. eG: multi-line support (Break the text line after a specific amount of letters).
Problem 2:
I'm trying to add a little speech bubble direction pointer to the speechbubble. Sorry for the way I'm describing it this way, don't know the word for it. But I'm talking about the following:
How could I add the following to my speechbubble?
I appreciate any sugestions and help.
The current example:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
ctx.font = "13px Helvetica";
var text = 'Speechbubble test';
component(ctx, ctx.measureText(text).width, 70, "#37f", 10, 10, 16, text);
function component(ctx, width, height, color, x, y, radius, text)
{
// Variables
var width = width + 40;
var height = height;
var x = x;
var y = y;
var radius = Math.min(radius, Math.min(width, height) / 2);
var color = color;
var pi2 = Math.PI * 2;
var r = radius;
var w = width;
var h = height;
// Transparent background
//ctx.fillStyle = "rgba(255, 255, 255, 0.5)";
ctx.fillStyle = color;
ctx.setTransform(1, 0, 0, 1, x, y);
// Draw arc
ctx.beginPath();
ctx.arc(r , r , r, pi2 * 0.5 , pi2 * 0.75);
ctx.arc(w - r, r, r, pi2 * 0.75, pi2);
ctx.arc(w - r, h - r, r, 0, pi2 * 0.25);
ctx.arc(r , h - r, r, pi2 * 0.25, pi2 * 0.5);
ctx.fill();
ctx.setTransform(1, 0, 0, 1, 0, 0);
// Text fillstyle
ctx.fillStyle = "#fff";
ctx.fillText(text, x + 20, y + 40);
}
<canvas width="500" height="500" id="canvas"></canvas>
The problem is that although the specs defines a way to measure height via a the TextMetrics object, no vendor has actually implemented it at current time.
So we have to cheat a bit to get the actual size from the font.
One way to do this is to temporary insert a DOM element and get the height from that:
console.log(getTextHeight("Hello", "20px sans-serif"));
function getTextHeight(txt, font) {
var el = document.createElement('div'), height;
el.style.cssText = "position:fixed;padding:0;left:-9999px;top:-9999px;font:" + font;
el.textContent = txt;
document.body.appendChild(el);
height = parseInt(getComputedStyle(el).getPropertyValue('height'), 10);
document.body.removeChild(el);
return height
}
For use with canvas just pass in context.font as your font argument:
var fontHeight = getTextHeight("Hello", ctx.font);
As to problem two:
You can break up the bottom line path so to speak, of the rounded rectangle by inserting lineTo() calls, like:
var ctx = c.getContext("2d"), r = 20, w = 290, h = 100, pi2 = Math.PI*2;
var ap = w * 0.2, aw = 20, ah = 30; //arrow position, width, height
ctx.translate(1.5,0.5);
// Rounded rectangle
ctx.beginPath();
ctx.arc(r , r , r, pi2 * 0.5 , pi2 * 0.75);
ctx.arc(w - r, r, r, pi2 * 0.75, pi2);
ctx.arc(w - r, h - r, r, 0, pi2 * 0.25); // bottom right corner
ctx.lineTo(w - ap, h); // inserts an arrow (following clock-wise)
ctx.lineTo(w - ap, h + ah);
ctx.lineTo(w - ap - aw, h);
ctx.arc(r , h - r, r, pi2 * 0.25, pi2 * 0.5); // bottom left corner
ctx.closePath();
ctx.stroke();
<canvas id=c></canvas>

How can i plot letter around a fabricjs circle

i have a circle added to canvas and then some text i would like wrapped around a circle.
here is what i have so far
var circle = new fabric.Circle({
top: 100,
left: 100,
radius: 100,
fill: '',
stroke: 'green',
});
canvas.add(circle);
var obj = "some text"
for(letter in obj){
var newLetter = new fabric.Text(obj[letter], {
top: 100,
left: 100
});
canvas.add(newLetter);
canvas.renderAll();
}
i have a tried a couple other solutions posted around the web but nothing working properly so far with fabric.
Circular Text.
I started this answer thinking it would be easy but it turned a little ugly. I rolled it back to a simpler version.
The problems I encountered are basic but there are no simple solutions..
Text going around the circle can end up upside down. Not good for
reading
The spacing. Because the canvas only gives a basic 2D transform I can
not scale the top and bottom of the text independently resulting in
text that either looks too widely spaced or too squashed.
I have an altogether alternative approch by it is way too heavy for an answer here. It involves a custom scan line render (a GPU hack of sorts) so you may try looking for something along those lines if text quality is paramount.
The problem I encounter were fixed by just ignoring them, always a good solution. LOL
How to render circular text on 2D canvas.
As there is no way to do it in one call I wrote a function that renders each character one at a time. I use ctx.measureText to get the size of the whole string to be drawn and then convert that into an angular pixel size. Then with a little adjustments for the various options, alignment, stretching, and direction (mirroring) I go through each character in the string one at a time, use ctx.measureText to measure it's size and then use ctx.setTransform to position rotate and scale the character, then just call ctx.fillText() rendering just that character.
It is a little slower than just the ctx.fillText()method but then fill text can't draw on circles can it.
Some calculations required.
To workout the angular size of a pixel for a given radius is trivial but often I see not done correctly. Because Javascript works in radians angular pixel size is just
var angularPixelSize = 1 / radius; // simple
Thus to workout what angle some text will occupy on a circle or given radius.
var textWidth = ctx.measureText("Hello").width;
var textAngularWidth = angularPixelSize * textWidth;
To workout the size of a single character.
var text = "This is some text";
var index = 2; // which character
var characterWidth = ctx.measureText(text[index]).width;
var characterAngularWidth = angularPixelSize * textWidth;
So you have the angular size you can now align the text on the circle, either centered, right or left. See the snippet code for details.
Then you need to loop through each character one at a time calculating the transformation, rendering the text, moving the correct angular distance for the next character until done.
var angle = ?? // the start angle
for(var i = 0; i < text.length; i += 1){ // for each character in the string
var c = text[i]; // get character
// get character angular width
var w = ctx.measureText(c).width * angularPixelSize;
// set the matrix to align the text. See code under next paragraph
...
...
// matrix set
ctx.fillText(c,0,0); // as the matrix set the origin just render at 0,0
angle += w;
}
The fiddly math part is setting the transform. I find it easier to work directly with the transformation matrix and that allows me to mess with scaling etc with out having to use too many transformation calls.
Set transform takes 6 numbers, first two are the direction of the x axis, the next two are the direction of the y axis and the last two are the translation from the canvas origin.
So to get the Y axis. The line from the circle center moving outward for each character we need the angle at which the character is being draw and to reduce misalignment (NOTE reduce not eliminate) the angular width so we can use the character's center to align it.
// assume angle is position and w is character angular width from above code
var xDx = Math.cos(angle + w / 2); // get x part of X axis direction
var xDy = Math.sin(angle + w / 2); // get y part of X axis direction
Now we have the normalised vector that will be the x axis. The character is draw from left to right along this axis. I construct the matrix in one go but I'll break it up below. Please NOTE that I made a boo boo in my snippet code with angles so the code is back to front (X is Y and Y is X)
Note that the snippet has the ability to fit text between two angles so I scale the x axis to allow this.
// assume scale is how much the text is squashed along its length.
ctx.setTransform(
xDx * scale, xDy * scale, // set the direction and size of a pixel for the X axis
-xDy, xDx, // the direction ot the Y axis is perpendicular so switch x and y
-xDy * radius + x, xdx * radius + y // now set the origin by scaling by radius and translating by the circle center
);
Well thats the math and logic to drawing a circular string. I am sorry but I dont use fabric.js so it may or may not have the option. But you can create your own function and render directly to the same canvas as fabric.js, as it does not exclude access. Though it will pay to save and restore the canvas state as fabric.js does not know of the state change.
Below is a snippet showing the above in practice. It is far from ideal but is about the best that can be done quickly using the existing canvas 2D API. Snippet has the two functions for measuring and drawing plus some basic usage examples.
function showTextDemo(){
/** Include fullScreenCanvas.js begin **/
var canvas = document.getElementById("canv");
if(canvas !== null){
document.body.removeChild(canvas);
}
canvas = (function () {
// creates a blank image with 2d context
canvas = document.createElement("canvas");
canvas.id = "canv";
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.style.position = "absolute";
canvas.style.top = "0px";
canvas.style.left = "0px";
canvas.ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
return canvas;
} ) ();
var ctx = canvas.ctx;
/** fullScreenCanvas.js end **/
// measure circle text
// ctx: canvas context
// text: string of text to measure
// x,y: position of center
// r: radius in pixels
//
// returns the size metrics of the text
//
// width: Pixel width of text
// angularWidth : angular width of text in radians
// pixelAngularSize : angular width of a pixel in radians
var measureCircleText = function(ctx, text, x, y, radius){
var textWidth;
// get the width of all the text
textWidth = ctx.measureText(text).width;
return {
width :textWidth,
angularWidth : (1 / radius) * textWidth,
pixelAngularSize : 1 / radius
}
}
// displays text alon a circle
// ctx: canvas context
// text: string of text to measure
// x,y: position of center
// r: radius in pixels
// start: angle in radians to start.
// [end]: optional. If included text align is ignored and the text is
// scalled to fit between start and end;
// direction
var circleText = function(ctx,text,x,y,radius,start,end,direction){
var i, textWidth, pA, pAS, a, aw, wScale, aligned, dir;
// save the current textAlign so that it can be restored at end
aligned = ctx.textAlign;
dir = direction ? 1 : -1;
// get the angular size of a pixel in radians
pAS = 1 / radius;
// get the width of all the text
textWidth = ctx.measureText(text).width;
// if end is supplied then fit text between start and end
if(end !== undefined){
pA = ((end - start) / textWidth) * dir;
wScale = (pA / pAS) * dir;
}else{ // if no end is supplied corret start and end for alignment
pA = -pAS * dir;
wScale = -1 * dir;
switch(aligned){
case "center": // if centered move around half width
start -= pA * (textWidth / 2);
end = start + pA * textWidth;
break;
case "right":
end = start;
start -= pA * textWidth;
break;
case "left":
end = start + pA * textWidth;
}
}
// some code to help me test. Left it here incase someone wants to underline
// rmove the following 3 lines if you dont need underline
ctx.beginPath();
ctx.arc(x,y,radius,end,start,end>start?true:false);
ctx.stroke();
ctx.textAlign = "center"; // align for rendering
a = start; // set the start angle
for (var i = 0; i < text.length; i += 1) { // for each character
// get the angular width of the text
aw = ctx.measureText(text[i]).width * pA;
var xDx = Math.cos(a + aw / 2); // get the yAxies vector from the center x,y out
var xDy = Math.sin(a + aw / 2);
if (xDy < 0) { // is the text upside down. If it is flip it
// sets the transform for each character scaling width if needed
ctx.setTransform(-xDy * wScale, xDx * wScale,-xDx,-xDy, xDx * radius + x,xDy * radius + y);
}else{
ctx.setTransform(-xDy * wScale, xDx * wScale, xDx, xDy, xDx * radius + x, xDy * radius + y);
}
// render the character
ctx.fillText(text[i],0,0);
a += aw;
}
ctx.setTransform(1,0,0,1,0,0);
ctx.textAlign = aligned;
}
// set up canvas
var w = canvas.width;
var h = canvas.height;
var cw = w / 2; // centers
var ch = h / 2;
var rad = (h / 2) * 0.9; // radius
// clear
ctx.clearRect(0, 0, w, h)
// the font
var fontSize = Math.floor(h/20);
if(h < 400){
var fontSize = 10;
}
ctx.font = fontSize + "px verdana";
// base settings
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
ctx.fillStyle = "#666";
ctx.strokeStyle = "#666";
// Text under stretched
circleText(ctx, "Test of circular text rendering", cw, ch, rad, Math.PI, 0, true);
// Text over stretchered
ctx.fillStyle = "Black";
circleText(ctx, "This text is over the top", cw, ch, rad, Math.PI, Math.PI * 2, true);
// Show centered text
rad -= fontSize + 4;
ctx.fillStyle = "Red";
// Use measureCircleText to get angular size
var tw = measureCircleText(ctx, "Centered", cw, ch, rad).angularWidth;
// centered bottom and top
circleText(ctx, "Centered", cw, ch, rad, Math.PI / 2, undefined, true);
circleText(ctx, "Centered", cw, ch, rad, -Math.PI * 0.5, undefined, false);
// left align bottom and top
ctx.textAlign = "left";
circleText(ctx, "Left Align", cw, ch, rad, Math.PI / 2 - tw * 0.6, undefined, true);
circleText(ctx, "Left Align Top", cw, ch, rad, -Math.PI / 2 + tw * 0.6, undefined, false);
// right align bottom and top
ctx.textAlign = "right";
circleText(ctx, "Right Align", cw, ch, rad, Math.PI / 2 + tw * 0.6, undefined, true);
circleText(ctx, "Right Align Top", cw, ch, rad, -Math.PI / 2 - tw * 0.6, undefined, false);
// Show base line at middle
ctx.fillStyle = "blue";
rad -= fontSize + fontSize;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
circleText(ctx, "Baseline Middle", cw, ch, rad, Math.PI / 2, undefined, true);
circleText(ctx, "Baseline Middle", cw, ch, rad, -Math.PI / 2, undefined, false);
// show baseline at top
ctx.fillStyle = "Green";
rad -= fontSize + fontSize;
ctx.textAlign = "center";
ctx.textBaseline = "top";
circleText(ctx, "Baseline top", cw, ch, rad, Math.PI / 2, undefined, true);
circleText(ctx, "Baseline top", cw, ch, rad, -Math.PI / 2, undefined, false);
}
showTextDemo();
window.addEventListener("resize",showTextDemo);

Cutting irregular shape on image

I am trying to cut an image into a particular shape using the canvas clip() method.
I have followed the following steps to do so:
Draw a rectangle.
Draw semi circles on each side. The right and bottom semi circles protrude outwards and the left and top semi circles are inwards.
The code snippet is provided below:
var canvasNode = this.hasNode();
var ctx = canvasNode && canvasNode.getContext('2d');
var image = new Image();
image.onload = function() {
ctx.drawImage(image, 0, 0, 512, 384);
};
image.src = "images/image.png";
var startX = 200;
var startY = 0;
var rectWidth = 150;
var rectHeight = 150;
var radius = 30;
//Main Rect
ctx.rect(startX, startY, rectWidth, rectHeight);
//Right arc
ctx.moveTo(startX+=rectWidth, startY+=(rectHeight/2));
ctx.arc(startX, startY, radius, 3 * Math.PI / 2, Math.PI / 2, false);
//Left arc
ctx.moveTo(startX-=(rectWidth / 2), startY+=(rectHeight / 2));
ctx.arc(startX, startY, radius, 0, Math.PI, true);
ctx.moveTo(startX-=(rectWidth / 2), startY-=(rectWidth / 2));
ctx.arc(startX, startY, radius, 3 * Math.PI / 2, Math.PI / 2, false);
ctx.clip();
The image that I am using is of size 800 x 600 (png). Please help me understand what I am doing wrong here.
Firstly, why are you using clip? You are currently just drawing semicircles, which works without clip.
Secondly, you are creating paths and clipping, but you never stroke the path. As a result, you won't see anything on the screen.
If you just stroke instead of clip, it works partially for me: http://jsfiddle.net/r6yAN/. You did not include the top semicircle though.
Edit: It seems like you're not using the best way of clipping. You draw a rectangle, but this also includes a line in the semicircle. You'd be better off if you draw each line/arc yourself like this: http://jsfiddle.net/CH6qB/6/.
The main idea is to move from point to point as in this image:
So first start at (startX, startY), then a line to (startX + lineWidth, startY), then an arc at (startX + rectWidth / 2, startY) from pi to 0 (counterclockwise), etc.
If you want to stroke the path as well after having drawn the image, it is a good idea to unclip again. Otherwise, the stroke will not be of great quality.
var canvasNode = document.getElementById('cv');
var ctx = canvasNode && canvasNode.getContext('2d');
var image = new Image();
image.onload = function() {
// draw the image, region has been clipped
ctx.drawImage(image, startX, startY);
// restore so that a stroke is not affected by clip
// (restore removes the clipping because we saved the path without clip below)
ctx.restore();
ctx.stroke();
};
image.src = "http://www.lorempixum.com/200/200/";
var startX = 200;
var startY = 0;
var rectWidth = 150;
var rectHeight = 150;
var radius = 30;
var lineWidth = rectWidth / 2 - radius;
var lineHeight = rectHeight / 2 - radius;
// typing pi is easier than Math.PI each time
var pi = Math.PI;
ctx.moveTo(startX, startY);
ctx.lineTo(startX + lineWidth, startY);
ctx.arc(startX + rectWidth / 2, startY,
radius,
pi, 0, true);
ctx.lineTo(startX + rectWidth, startY);
ctx.lineTo(startX + rectWidth, startY + lineHeight);
ctx.arc(startX + rectWidth, startY + rectHeight / 2,
radius,
-pi / 2, pi / 2, false);
ctx.lineTo(startX + rectWidth, startY + rectHeight);
ctx.lineTo(startX + rectWidth - lineWidth, startY + rectHeight);
ctx.arc(startX + rectWidth / 2, startY + rectHeight,
radius,
0, pi, false);
ctx.lineTo(startX, startY + rectHeight);
ctx.lineTo(startX, startY + rectHeight - lineHeight);
ctx.arc(startX, startY + rectHeight / 2,
radius,
pi/2, pi*3/2, true);
ctx.lineTo(startX, startY);
ctx.save(); // Save the current state without clip
ctx.clip();

How to draw an oval in html5 canvas?

There doesnt seem to be a native function to draw an oval-like shape. Also i am not looking for the egg-shape.
Is it possible to draw an oval with 2 bezier curves?
Somebody expierenced with that?
My purpose is to draw some eyes and actually im just using arcs.
Thanks in advance.
Solution
So scale() changes the scaling for all next shapes.
Save() saves the settings before and restore is used to restore the settings to draw new shapes without scaling.
Thanks to Jani
ctx.save();
ctx.scale(0.75, 1);
ctx.beginPath();
ctx.arc(20, 21, 10, 0, Math.PI*2, false);
ctx.stroke();
ctx.closePath();
ctx.restore();
updates:
scaling method can affect stroke width appearance
scaling method done right can keep stroke width intact
canvas has ellipse method that Chrome now supports
added updated tests to JSBin
JSBin Testing Example (updated to test other's answers for comparison)
Bezier - draw based on top left containing rect and width/height
Bezier with Center - draw based on center and width/height
Arcs and Scaling - draw based on drawing circle and scaling
see Deven Kalra's answer
Quadratic Curves - draw with quadratics
test appears to not draw quite the same, may be implementation
see oyophant's answer
Canvas Ellipse - using W3C standard ellipse() method
test appears to not draw quite the same, may be implementation
see Loktar's answer
Original:
If you want a symmetrical oval you could always create a circle of radius width, and then scale it to the height you want (edit: notice this will affect stroke width appearance - see acdameli's answer), but if you want full control of the ellipse here's one way using bezier curves.
<canvas id="thecanvas" width="400" height="400"></canvas>
<script>
var canvas = document.getElementById('thecanvas');
if(canvas.getContext)
{
var ctx = canvas.getContext('2d');
drawEllipse(ctx, 10, 10, 100, 60);
drawEllipseByCenter(ctx, 60,40,20,10);
}
function drawEllipseByCenter(ctx, cx, cy, w, h) {
drawEllipse(ctx, cx - w/2.0, cy - h/2.0, w, h);
}
function drawEllipse(ctx, x, y, w, h) {
var kappa = .5522848,
ox = (w / 2) * kappa, // control point offset horizontal
oy = (h / 2) * kappa, // control point offset vertical
xe = x + w, // x-end
ye = y + h, // y-end
xm = x + w / 2, // x-middle
ym = y + h / 2; // y-middle
ctx.beginPath();
ctx.moveTo(x, ym);
ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
//ctx.closePath(); // not used correctly, see comments (use to close off open path)
ctx.stroke();
}
</script>
Here is a simplified version of solutions elsewhere. I draw a canonical circle, translate and scale and then stroke.
function ellipse(context, cx, cy, rx, ry){
context.save(); // save state
context.beginPath();
context.translate(cx-rx, cy-ry);
context.scale(rx, ry);
context.arc(1, 1, 1, 0, 2 * Math.PI, false);
context.restore(); // restore to original state
context.stroke();
}
There is now a native ellipse function for canvas, very similar to the arc function although now we have two radius values and a rotation which is awesome.
ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise)
Live Demo
ctx.ellipse(100, 100, 10, 15, 0, 0, Math.PI*2);
ctx.fill();
Only seems to work in Chrome currently
The bezier curve approach is great for simple ovals. For more control, you can use a loop to draw an ellipse with different values for the x and y radius (radiuses, radii?).
Adding a rotationAngle parameter allows the oval to be rotated around its center by any angle. Partial ovals can be drawn by changing the range (var i) over which the loop runs.
Rendering the oval this way allows you to determine the exact x,y location of all points on the line. This is useful if the postion of other objects depend on the location and orientation of the oval.
Here is an example of the code:
for (var i = 0 * Math.PI; i < 2 * Math.PI; i += 0.01 ) {
xPos = centerX - (radiusX * Math.sin(i)) * Math.sin(rotationAngle * Math.PI) + (radiusY * Math.cos(i)) * Math.cos(rotationAngle * Math.PI);
yPos = centerY + (radiusY * Math.cos(i)) * Math.sin(rotationAngle * Math.PI) + (radiusX * Math.sin(i)) * Math.cos(rotationAngle * Math.PI);
if (i == 0) {
cxt.moveTo(xPos, yPos);
} else {
cxt.lineTo(xPos, yPos);
}
}
See an interactive example here: http://www.scienceprimer.com/draw-oval-html5-canvas
You could also try using non-uniform scaling. You can provide X and Y scaling, so simply set X or Y scaling larger than the other, and draw a circle, and you have an ellipse.
You need 4 bezier curves (and a magic number) to reliably reproduce an ellipse. See here:
www.tinaja.com/glib/ellipse4.pdf
Two beziers don't accurately reproduce an ellipse. To prove this, try some of the 2 bezier solutions above with equal height and width - they should ideally approximate a circle but they won't. They'll still look oval which goes to prove they aren't doing what they are supposed to.
Here's something that should work:
http://jsfiddle.net/BsPsj/
Here's the code:
function ellipse(cx, cy, w, h){
var ctx = canvas.getContext('2d');
ctx.beginPath();
var lx = cx - w/2,
rx = cx + w/2,
ty = cy - h/2,
by = cy + h/2;
var magic = 0.551784;
var xmagic = magic*w/2;
var ymagic = h*magic/2;
ctx.moveTo(cx,ty);
ctx.bezierCurveTo(cx+xmagic,ty,rx,cy-ymagic,rx,cy);
ctx.bezierCurveTo(rx,cy+ymagic,cx+xmagic,by,cx,by);
ctx.bezierCurveTo(cx-xmagic,by,lx,cy+ymagic,lx,cy);
ctx.bezierCurveTo(lx,cy-ymagic,cx-xmagic,ty,cx,ty);
ctx.stroke();
}
I did a little adaptation of this code (partially presented by Andrew Staroscik) for peoplo who do not want a so general ellipse and who have only the greater semi-axis and the excentricity data of the ellipse (good for astronomical javascript toys to plot orbits, for instance).
Here you go, remembering that one can adapt the steps in i to have a greater precision in the drawing:
/* draw ellipse
* x0,y0 = center of the ellipse
* a = greater semi-axis
* exc = ellipse excentricity (exc = 0 for circle, 0 < exc < 1 for ellipse, exc > 1 for hyperbole)
*/
function drawEllipse(ctx, x0, y0, a, exc, lineWidth, color)
{
x0 += a * exc;
var r = a * (1 - exc*exc)/(1 + exc),
x = x0 + r,
y = y0;
ctx.beginPath();
ctx.moveTo(x, y);
var i = 0.01 * Math.PI;
var twoPi = 2 * Math.PI;
while (i < twoPi) {
r = a * (1 - exc*exc)/(1 + exc * Math.cos(i));
x = x0 + r * Math.cos(i);
y = y0 + r * Math.sin(i);
ctx.lineTo(x, y);
i += 0.01;
}
ctx.lineWidth = lineWidth;
ctx.strokeStyle = color;
ctx.closePath();
ctx.stroke();
}
My solution is a bit different than all of these. Closest I think is the most voted answer above though, but I think this way is a bit cleaner and easier to comprehend.
http://jsfiddle.net/jaredwilli/CZeEG/4/
function bezierCurve(centerX, centerY, width, height) {
con.beginPath();
con.moveTo(centerX, centerY - height / 2);
con.bezierCurveTo(
centerX + width / 2, centerY - height / 2,
centerX + width / 2, centerY + height / 2,
centerX, centerY + height / 2
);
con.bezierCurveTo(
centerX - width / 2, centerY + height / 2,
centerX - width / 2, centerY - height / 2,
centerX, centerY - height / 2
);
con.fillStyle = 'white';
con.fill();
con.closePath();
}
And then use it like this:
bezierCurve(x + 60, y + 75, 80, 130);
There are a couple use examples in the fiddle, along with a failed attempt to make one using quadraticCurveTo.
I like the Bezier curves solution above. I noticed the scale also affects the line width so if you're trying to draw an ellipse that is wider than it is tall, your top and bottom "sides" will appear thinner than your left and right "sides"...
a good example would be:
ctx.lineWidth = 4;
ctx.scale(1, 0.5);
ctx.beginPath();
ctx.arc(20, 20, 10, 0, Math.PI * 2, false);
ctx.stroke();
you should notice the width of the line at the peak and valley of the ellipse are half as wide as at the left and right apexes (apices?).
Chrome and Opera support ellipse method for canvas 2d context, but IE,Edge,Firefox and Safari don't support it.
We can implement the ellipse method by JS or use a third-party polyfill.
ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise)
Usage example:
ctx.ellipse(20, 21, 10, 10, 0, 0, Math.PI*2, true);
You can use a canvas-5-polyfill to provide ellipse method.
Or just paste some js code to provide ellipse method:
if (CanvasRenderingContext2D.prototype.ellipse == undefined) {
CanvasRenderingContext2D.prototype.ellipse = function(x, y, radiusX, radiusY,
rotation, startAngle, endAngle, antiClockwise) {
this.save();
this.translate(x, y);
this.rotate(rotation);
this.scale(radiusX, radiusY);
this.arc(0, 0, 1, startAngle, endAngle, antiClockwise);
this.restore();
}
}
Yes, it is possible with two bezier curves - here's a brief tutorial/example:
http://www.williammalone.com/briefs/how-to-draw-ellipse-html5-canvas/
Since nobody came up with an approach using the simpler quadraticCurveTo I am adding a solution for that. Simply replace the bezierCurveTo calls in the #Steve's answer with this:
ctx.quadraticCurveTo(x,y,xm,y);
ctx.quadraticCurveTo(xe,y,xe,ym);
ctx.quadraticCurveTo(xe,ye,xm,ye);
ctx.quadraticCurveTo(x,ye,x,ym);
You may also remove the closePath. The oval is looking slightly different though.
This is another way of creating an ellipse like shape, although it uses the "fillRect()" function this can be used be changing the arguments in the fillRect() function.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sine and cosine functions</title>
</head>
<body>
<canvas id="trigCan" width="400" height="400"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("trigCan"), ctx = canvas.getContext('2d');
for (var i = 0; i < 360; i++) {
var x = Math.sin(i), y = Math.cos(i);
ctx.stroke();
ctx.fillRect(50 * 2 * x * 2 / 5 + 200, 40 * 2 * y / 4 + 200, 10, 10, true);
}
</script>
</body>
</html>
With this you can even draw segments of an ellipse:
function ellipse(color, lineWidth, x, y, stretchX, stretchY, startAngle, endAngle) {
for (var angle = startAngle; angle < endAngle; angle += Math.PI / 180) {
ctx.beginPath()
ctx.moveTo(x, y)
ctx.lineTo(x + Math.cos(angle) * stretchX, y + Math.sin(angle) * stretchY)
ctx.lineWidth = lineWidth
ctx.strokeStyle = color
ctx.stroke()
ctx.closePath()
}
}
http://jsfiddle.net/FazAe/1/
Here's a function I wrote that uses the same values as the ellipse arc in SVG. X1 & Y1 are the last coordinates, X2 & Y2 are the end coordinates, radius is a number value and clockwise is a boolean value. It also assumes your canvas context has already been defined.
function ellipse(x1, y1, x2, y2, radius, clockwise) {
var cBx = (x1 + x2) / 2; //get point between xy1 and xy2
var cBy = (y1 + y2) / 2;
var aB = Math.atan2(y1 - y2, x1 - x2); //get angle to bulge point in radians
if (clockwise) { aB += (90 * (Math.PI / 180)); }
else { aB -= (90 * (Math.PI / 180)); }
var op_side = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)) / 2;
var adj_side = Math.sqrt(Math.pow(radius, 2) - Math.pow(op_side, 2));
if (isNaN(adj_side)) {
adj_side = Math.sqrt(Math.pow(op_side, 2) - Math.pow(radius, 2));
}
var Cx = cBx + (adj_side * Math.cos(aB));
var Cy = cBy + (adj_side * Math.sin(aB));
var startA = Math.atan2(y1 - Cy, x1 - Cx); //get start/end angles in radians
var endA = Math.atan2(y2 - Cy, x2 - Cx);
var mid = (startA + endA) / 2;
var Mx = Cx + (radius * Math.cos(mid));
var My = Cy + (radius * Math.sin(mid));
context.arc(Cx, Cy, radius, startA, endA, clockwise);
}
If you want the ellipse to fully fit inside a rectangle, it's really like this:
function ellipse(canvasContext, x, y, width, height){
var z = canvasContext, X = Math.round(x), Y = Math.round(y), wd = Math.round(width), ht = Math.round(height), h6 = Math.round(ht/6);
var y2 = Math.round(Y+ht/2), xw = X+wd, ym = Y-h6, yp = Y+ht+h6, cs = cards, c = this.card;
z.beginPath(); z.moveTo(X, y2); z.bezierCurveTo(X, ym, xw, ym, xw, y2); z.bezierCurveTo(xw, yp, X, yp, X, y2); z.fill(); z.stroke();
return z;
}
Make sure your canvasContext.fillStyle = 'rgba(0,0,0,0)'; for no fill with this design.

Categories

Resources