find coordinates to draw square inside circle - html

How to compute the starting co-ordinates to draw a square inside a cirle?
Function Draws the circular spectrum .
Now help me to find the starting coordinates to draw the rectangle inside the circle
Gradient.prototype.renderSpectrum = function() {
var radius = this.width / 2;
var toRad = (2 * Math.PI) / 360;
var step = 1 / radius;
this.ctx.clearRect(0, 0, this.width, this.height);
for(var i = 0; i < 360; i += step) {
var rad = i * toRad;
this.ctx.strokeStyle = 'hsl(' + i + ', 100%, 50%)';
this.ctx.beginPath();
this.ctx.moveTo(radius, radius);
this.ctx.lineTo(radius + radius * Math.cos(rad), radius + radius * Math.sin(rad));
this.ctx.stroke();
}
this.ctx.fillStyle = 'rgb(255, 255, 255)';
this.ctx.beginPath();
this.ctx.arc(radius, radius, radius * 0.8, 0, Math.PI * 2, true);
this.ctx.closePath();
return this.ctx.fill();
}
Function to draw the square
Gradient.prototype.renderGradient = function() {
var color, colors, gradient, index, xy, _i, _len, _ref, _ref1;
xy = arguments[0], colors = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
gradient = (_ref = this.ctx).createLinearGradient.apply(_ref, [0, 0].concat(__slice.call(xy)));
gradient.addColorStop(0, (_ref1 = colors.shift()) != null ? _ref1.toString() : void 0);
for (index = _i = 0, _len = colors.length; _i < _len; index = ++_i) {
color = colors[index];
gradient.addColorStop(index + 1 / colors.length, color.toString());
}
this.ctx.fillStyle = gradient;
this.renderSpectrum();
return this.ctx.fillRect(?, ?, this.width * 0.8, this.height * 0.8);
};

To fit a square inside a circle you can use something like this (adopt as needed):
Live example
/**
* ctx - context
* cx/cy - center of circle
* radius - radius of circle
*/
function squareInCircle(ctx, cx, cy, radius) {
var side = Math.sqrt(radius * radius * 2), // calc side length of square
half = side * 0.5; // position offset
ctx.strokeRect(cx - half, cy - half, side, side);
}
Just replace strokeRect() with fillRect().
Which will result in this (circle added for reference):
Adopting it for general usage:
function getSquareInCircle(cx, cy, radius) {
var side = Math.sqrt(radius * radius * 2), // calc side length of square
half = side * 0.5; // position offset
return {
x: cx - half,
y: cy - half,
w: side,
h: side
}
}
Then in your method:
Gradient.prototype.renderGradient = function() {
var color, colors, gradient, index, xy, _i, _len, _ref, _ref1;
xy = arguments[0], colors = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
gradient = (_ref = this.ctx).createLinearGradient.apply(_ref, [0, 0].concat(__slice.call(xy)));
gradient.addColorStop(0, (_ref1 = colors.shift()) != null ? _ref1.toString() : void 0);
for (index = _i = 0, _len = colors.length; _i < _len; index = ++_i) {
color = colors[index];
gradient.addColorStop(index + 1 / colors.length, color.toString());
}
this.ctx.fillStyle = gradient;
this.renderSpectrum();
// supply the proper position/radius here:
var square = getSquareInCircle(centerX, centerY, radius);
return this.ctx.fillRect(square.x, square.y, square.w, square.h);
};

Here is how I computed the co ordinates to draw square inside a circle
1)Get the coordinates of a inner circle at 135 degree
using the formula
x = rad + rad * Math.cos(135 * ( 2 Math.PI / 360);
y = rad - rad * Math.sin(135 * ( 2 Math.PI / 360);
2) then pyhthogoram therom to find the width if the square
width = Math.sqrt(rad * rad / 2);

Related

Clip + Arc leads to an unwanted closing of the path, while Clip + Rect shows the expected behavior

Question:
Why does CanvasRenderingContext2D.clip() closes an additional path when applying it to a collection of CanvasRenderingContext2D.arc() sampled along the path of a quadratic curve?
Background
I am trying to create a path of quadratic segments with a longitudinal color split. Based on a comment to the question "Square curve with lengthwise color division" I am trying to accomplish this goal by going through the following steps:
Draw the quadratic path
Sample point on the quadratic curve
Create a clipping region and draw a cycle at each sampled point
let region = new Path2D();
for (j = 0; j < pointsQBez.length; j++) {
region.arc(pointsQBez[j].x, pointsQBez[j].y, 4, 0, 2 * Math.PI );
}
ctx.clip(region)
Split the canvas into two segments based on the curve
Calculate the intersection of the start- and end-segment with the canvas border
Close the path (first clipping region)
Draw a rectangle over the whole canvas (second clipping region)
Fill in the two regions created in step four
Steps 3, 4, and 5 in pictures:
Issue
The pink part in the third image above should have the same thickness as the turquoise.
But for some strange reason, the whole inner part of the curve gets filled in.
Additional observations
This behaviour does not show when using CanvasRenderingContext2D.rect() instead of CanvasRenderingContext2D.arc():
When using CanvasRenderingContext2D.arc(), the inner part of the curve that is filled in is not consistent
Because rect does include a call to closePath() while arc doesn't.
Two ways of working around that:
You can call closePath() after each arc:
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const pointsQBez = [];
const cx = 75;
const cy = 75;
const rad = 50;
for(let i = 0; i < 180; i++) {
const a = (Math.PI / 180) * i - Math.PI / 2;
const x = cx + Math.cos(a) * rad;
const y = cy + Math.sin(a) * rad;
pointsQBez.push({ x, y });
}
let region = new Path2D();
for (const {x, y} of pointsQBez) {
region.arc(x, y, 4, 0, 2 * Math.PI);
region.closePath();
}
ctx.clip(region);
ctx.fillStyle = "red";
ctx.fillRect(0, 0, canvas.width, canvas.height);
<canvas></canvas>
Or you can moveTo() the entry point of your arc:
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const pointsQBez = [];
const cx = 75;
const cy = 75;
const rad = 50;
for(let i = 0; i < 180; i++) {
const a = (Math.PI / 180) * i - Math.PI / 2;
const x = cx + Math.cos(a) * rad;
const y = cy + Math.sin(a) * rad;
pointsQBez.push({ x, y });
}
let region = new Path2D();
for (const {x, y} of pointsQBez) {
region.moveTo(x + 4, y); // x + arc radius
region.arc(x, y, 4, 0, 2 * Math.PI);
}
ctx.clip(region);
ctx.fillStyle = "red";
ctx.fillRect(0, 0, canvas.width, canvas.height);
<canvas></canvas>

Draw Line Arrowhead Without Rotating in Canvas

Most code to drawing arrowheads in html canvas involves rotating the canvas context and drawing the lines.
My use case is to draw them using trigonometry without rotating the canvas. or is that vector algorithm you call it? Help is appreciated.
This is what I have (forgot where I got most of the code). Draws 2 arrowheads on start and end based on the last 2 parameters arrowStart and arrowEnd which are boolean.
drawLineArrowhead: function(context, arrowStart, arrowEnd) {
// Place start end points here.
var x1 = 0;
var y1 = 0;
var x2 = 0;
var y2 = 0;
var distanceFromLine = 6;
var arrowLength = 9;
var dx = x2 - x1;
var dy = y2 - y1;
var angle = Math.atan2(dy, dx);
var length = Math.sqrt(dx * dx + dy * dy);
context.translate(x1, y1);
context.rotate(angle);
context.beginPath();
context.moveTo(0, 0);
context.lineTo(length, 0);
if (arrowStart) {
context.moveTo(arrowLength, -distanceFromLine);
context.lineTo(0, 0);
context.lineTo(arrowLength, distanceFromLine);
}
if (arrowEnd) {
context.moveTo(length - arrowLength, -distanceFromLine);
context.lineTo(length, 0);
context.lineTo(length - arrowLength, distanceFromLine);
}
context.stroke();
context.setTransform(1, 0, 0, 1, 0, 0);
},
See the code below, just a bit of trigonometry.
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.lineCap = "round";
ctx.lineWidth = 5;
function drawLineArrowhead(p1, p2, startSize, endSize) {
ctx.beginPath()
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.y);
if (startSize > 0) {
lineAngle = Math.atan2(p2.y - p1.y, p2.x - p1.x);
delta = Math.PI/6
for (i=0; i<2; i++) {
ctx.moveTo(p1.x, p1.y);
x = p1.x + startSize * Math.cos(lineAngle + delta)
y = p1.y + startSize * Math.sin(lineAngle + delta)
ctx.lineTo(x, y);
delta *= -1
}
}
if (endSize > 0) {
lineAngle = Math.atan2(p1.y - p2.y, p1.x - p2.x);
delta = Math.PI/6
for (i=0; i<2; i++) {
ctx.moveTo(p2.x, p2.y);
x = p2.x + endSize * Math.cos(lineAngle + delta)
y = p2.y + endSize * Math.sin(lineAngle + delta)
ctx.lineTo(x, y);
delta *= -1
}
}
ctx.stroke();
}
drawLineArrowhead({x:10, y:10}, {x:100, y:20}, 0, 30)
drawLineArrowhead({x:20, y:25}, {x:140, y:120}, 20, 20)
drawLineArrowhead({x:140, y:20}, {x:80, y:50} , 20, 0)
drawLineArrowhead({x:150, y:20}, {x:150, y:90}, 20, 5)
drawLineArrowhead({x:180, y:90}, {x:180, y:20}, 20, 5)
drawLineArrowhead({x:200, y:10}, {x:200, y:140}, 10, 10)
drawLineArrowhead({x:220, y:140}, {x:220, y:10}, 10, 20)
<canvas id="canvas">
If you run it you should see a few samples.
The drawLineArrowhead has 4 parameters (p1, p2, startSize, endSize)
the first two are the starting-point and end-point of the line, the last two are arrow size, just to give some control to the final user over how big are those arrows at the end, if we want to remove them we set to 0.

Chart Label text rotation

I am using very similar code to create a pie chart using canvas as per this article:
http://wickedlysmart.com/how-to-make-a-pie-chart-with-html5s-canvas/
As you can see from this image, there are cases where the labels are upside down:
Here is the code that writes the labels to the graph:
var drawSegmentLabel = function(canvas, context, i) {
context.save();
var x = Math.floor(canvas.width / 2);
var y = Math.floor(canvas.height / 2);
var degrees = sumTo(data, i);
var angle = degreesToRadians(degrees);
context.translate(x, y);
context.rotate(angle);
context.textAlign = 'right';
var fontSize = Math.floor(canvas.height / 32);
context.font = fontSize + 'pt Helvetica';
var dx = Math.floor(canvas.width * 0.3) - 20;
var dy = Math.floor(canvas.height * 0.05);
context.fillText(labels[i], dx, dy);
context.restore();
};
I am trying to rectify this so the text is always readable and not upside down but cant work out how to do it!
Here's my solution! (A little kludgey but seems to work on the basic example, I haven't tested in on edge cases...)
var drawSegmentLabel = function(canvas, context, i) {
context.save();
var x = Math.floor(canvas.width / 2);
var y = Math.floor(canvas.height / 2);
var angle;
var angleD = sumTo(data, i);
var flip = (angleD < 90 || angleD > 270) ? false : true;
context.translate(x, y);
if (flip) {
angleD = angleD-180;
context.textAlign = "left";
angle = degreesToRadians(angleD);
context.rotate(angle);
context.translate(-(x + (canvas.width * 0.5))+15, -(canvas.height * 0.05)-10);
}
else {
context.textAlign = "right";
angle = degreesToRadians(angleD);
context.rotate(angle);
}
var fontSize = Math.floor(canvas.height / 25);
context.font = fontSize + "pt Helvetica";
var dx = Math.floor(canvas.width * 0.5) - 10;
var dy = Math.floor(canvas.height * 0.05);
context.fillText(labels[i], dx, dy);
context.restore();
};
To display the text in the correct way you have to check if the rotation angle is between 90 and 270 degree. If it is then you know the text will be display upside down.
To switch it correctly you then have to rotate you canvas of planed rotation - 180 degree and then to align it in left not right :
var drawSegmentLabel = function(canvas, context, i) {
context.save();
var x = Math.floor(canvas.width / 2);
var y = Math.floor(canvas.height / 2);
var degrees = sumTo(data, i);
var angle = 0;
if (degree > 90 && degree < 270)
angle = degreesToRadians(degrees - 180);
else
angle = degreesToRadians(degrees);
context.translate(x, y);
context.rotate(angle);
context.textAlign = 'right';
var fontSize = Math.floor(canvas.height / 32);
context.font = fontSize + 'pt Helvetica';
var dx = Math.floor(canvas.width * 0.3) - 20;
if (degree > 90 && degree < 270)
dx = 20;
var dy = Math.floor(canvas.height * 0.05);
context.fillText(labels[i], dx, dy);
context.restore();
};

HTML Canvas - Dotted stroke around circle

I do know there is no native support for doing dotted stroke lines rendered on a canvas, but I have seen the clever ways people have been able to generate support for this.
What I am wondering is if there is any way to translate this to allow for rendering dotted strokes around shapes (specifically circles)?
the simplest way using context.setLineDash()
ctx.setLineDash([5, 5]);
ctx.beginPath();
ctx.arc(100, 60, 50, 0, Math.PI * 2);
ctx.closePath();
ctx.stroke();
Live Demo
calcPointsCirc takes 4 arguments, the center x/y, the radius, and the length of the dashes. It returns an array of points, x,y,ex,ey. You can just loop through the points to draw the dashed circle. There's probably much more elegant ways to do this but figured Id give it a shot.
function calcPointsCirc( cx,cy, rad, dashLength)
{
var n = rad/dashLength,
alpha = Math.PI * 2 / n,
pointObj = {},
points = [],
i = -1;
while( i < n )
{
var theta = alpha * i,
theta2 = alpha * (i+1);
points.push({x : (Math.cos(theta) * rad) + cx, y : (Math.sin(theta) * rad) + cy, ex : (Math.cos(theta2) * rad) + cx, ey : (Math.sin(theta2) * rad) + cy});
i+=2;
}
return points;
}
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
canvas.width = canvas.height= 200;
var pointArray= calcPointsCirc(50,50,50, 1);
ctx.strokeStyle = "rgb(255,0,0)";
ctx.beginPath();
for(p = 0; p < pointArray.length; p++){
ctx.moveTo(pointArray[p].x, pointArray[p].y);
ctx.lineTo(pointArray[p].ex, pointArray[p].ey);
ctx.stroke();
}
ctx.closePath();
If all else fails you can always loop a variable from 0 to 2*pi, skipping every step items and drawing on every other step items points at sin(angle)*radius+centerx, cos(angle)*radius+centery.
There you go, home-made dotted circle :)
My JavaScript Path library implements dashed and dotted drawing of arbitrary paths (which can be composed of any number of straight or curved segments), including ellipses. Download it and check out the examples.
I was looking for a dashed-circle for my game and after reading all of the pages I have written a class in typescript it works very well. If anybody looks for the dashed-circle in typescript, it is here;
export class DashedCircle
{
centerX: number;
centerY: number;
radius: number;
color: string;
dashSize: number;
ctx: CanvasRenderingContext2D;
constructor(ctx:CanvasRenderingContext2D, centerX: number, centerY: number, radius: number, color: string, dashSize: number)
{
this.ctx = ctx;
this.centerX = centerX;
this.centerY = centerY;
this.radius = radius;
this.color = color;
this.dashSize = dashSize;
}
CalculateCirclePoints()
{
var n = this.radius / this.dashSize;
var alpha = Math.PI * 2 / n;
var pointObj = {};
var points = [];
var i = -1;
while (i < n)
{
var theta = alpha * i;
var theta2 = alpha * (i + 1);
points.push({
x: (Math.cos(theta) * this.radius) + this.centerX,
y: (Math.sin(theta) * this.radius) + this.centerY,
ex: (Math.cos(theta2) * this.radius) + this.centerX,
ey: (Math.sin(theta2) * this.radius) + this.centerY });
i += 2;
}
return points;
}
Draw()
{
var points = this.CalculateCirclePoints();
this.ctx.strokeStyle = this.color;
this.ctx.beginPath();
for (var p = 0; p < points.length; p++)
{
this.ctx.moveTo(points[p].x, points[p].y);
this.ctx.lineTo(points[p].ex, points[p].ey);
this.ctx.stroke();
}
this.ctx.closePath();
}
}

How to produce such page flip effects in Canvas?

google has published an e-book : http://www.20thingsilearned.com/
the reading experience is kind of fun.
I notice they used canvas to produce the page flip effects over reading areas.
Technically, you can draw a customized shape, filled with gradient, decorated with shadow.
but the shape has to be drawn with two beizer curves (for top and bottom edges) and two straight lines.
The problem is how to dynamically draw those two beizer curves. I spent a whole day to draw these two curves. here is some code of.
Does anyone knows how to produce the same effects on Google's ebook.
or i basically ran into wrong direction?
/**
* PageFlip effects using HTML Canvas
* #author RobinQu
* #version 0.1
*/
/*global x$ */
var elf = {};
elf.fx = {};
elf.fx.pageflip = {
/**
* initialize the pageflip
* #param {String} cId The id of canvas element
*/
init: function(cId, width, height) {
var canvas,
ctx;
this.$ = x$("#" + cId);
canvas = this.canvas = this.$[0];
this.width = canvas.width = width;
this.height = canvas.height = height;
this.margin = 60;
this.context = canvas.getContext("2d");
//this.bind();
},
bind: function() {
this.$.on("mouseover", this.beginRoll.bind(this));
this.$.on("mousemove", this.doRoll.bind(this));
this.$.on("mouseout", this.endRoll.bind(this));
},
_over: false,
beginRoll: function() {
this._over = true;
},
_clear: function() {
var ctx = this.context;
ctx.clearRect(0, 0, this.width, this.height);
var w = this.width;
this.canvas.width = 1;
this.canvas.width = w;
},
doRoll: function(e) {
//offset, plus scroll; client, no scroll
if (this._over) {
//console.log(e.offsetX, e.offsetY, e.clientX, e.clientY);
var x = e.offsetX,
y = e.offsetY,
ctx = this.context,
startx = x,
starty = x / this.width * this.margin,
endx = (this.width - x)/2 + x,
endy = this.margin + 8,
cp1x = x + 10,
cp1y = Math.min(this.margin * Math.sin(x * Math.PI / this.width), 5),
cp2x = endx - 10,
cp2y = Math.min(this.margin * Math.cos(x * Math.PI / this.width), 5);
console.log(this.margin * Math.sin(x * Math.PI / this.width));
//enxy = this.margin * Math.sin(x * Math.PI * 2 / this.width),
//cp2x = ;
console.log(this.width, this.height);
this._clear();
ctx.beginPath();
ctx.moveTo(startx, starty);
ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, endx, endy);
ctx.strokeStyle = "#000";
ctx.stroke();
}
},
endRoll: function() {
this._over = false;
}
};