JavaScript - determine if two circles will intersect along their path - javascript

var circleA = {
x: 100,
y: 40,
radius: 20,
color: '63, 81, 181',
pathx: 220,
pathy: 150
}
var circleB = {
x: 250,
y: 50,
radius: 30,
color: '76, 175, 80',
pathx: 120,
pathy: 140
}
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = 500;
var centerY = 500;
//draw circle A
context.beginPath();
context.arc(circleA.x, circleA.y, circleA.radius, 0, 2 * Math.PI, false);
context.fillStyle = "rgba(" + circleA.color + ", 1)";
context.fill();
//draw circle A path destination
context.beginPath();
context.arc(circleA.pathx, circleA.pathy, circleA.radius, 0, 2 * Math.PI, false);
context.fillStyle = "rgba(" + circleA.color + ", 0.5)";
context.fill();
//draw line in circle A path
context.beginPath();
context.moveTo(circleA.x,circleA.y);
context.lineTo(circleA.pathx,circleA.pathy);
context.strokeStyle = "rgba(" + circleA.color + ", 1)";
context.stroke();
//draw circle B
context.beginPath();
context.arc(circleB.x, circleB.y, circleB.radius, 0, 2 * Math.PI, false);
context.fillStyle = "rgba(" + circleB.color + ", 1)";
context.fill();
//draw circle B path destination
context.beginPath();
context.arc(circleB.pathx, circleB.pathy, circleA.radius, 0, 2 * Math.PI, false);
context.fillStyle = "rgba(" + circleB.color + ", 0.5)";
context.fill();
//draw line in circle A path
context.beginPath();
context.moveTo(circleB.x,circleB.y);
context.lineTo(circleB.pathx,circleB.pathy);
context.strokeStyle = "rgba(" + circleB.color + ", 1)";
context.stroke();
//I NEED HELP HERE - i have no idea how to calculate this
function willCollide(ca_start, ca_end, cb_start, cb_end)
{
var RSum = circleA.radius + circleB.radius;
var t = 10;
var a = getPos(circleA, t);
var b = getPos(circleB, t);
var distance = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
var sum = RSum*=2;
context.font = "20px Arial";
context.fillText('distance: ' + distance + " sum: " + sum,10,200);
}
function getPos(circle, t)
{
//position changes
var dax = (circle.pathx - circle.x);
var day = (circle.pathy - circle.y);
//normalize components
var lenA = Math.sqrt(dax * dax + day * day);
dax = dax / lenA;
day = day / lenA;
//position vs time
var ax = circleA.x + dax * t;
var ay = circleA.y + day * t;
return {
x: ax,
y: ay
}
}
willCollide(
{ x: circleA.x, y: circleA.y },
{ x: circleA.pathx, y: circleA.pathy },
circleA.radius,
{ x: circleB.x, y: circleB.y },
{ x: circleB.pathx, y: circleB.pathy },
circleB.radius
);
body {
margin: 0px;
padding: 0px;
}
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
</body>
</html>
I have circles running around in space with a given path on each frame.
so I can say that circle A will go to xy(10, 8) and that circle B will go to xy(5, -3).
and I need to make sure the path each circle is going is clear and that there is no other circle that will go on that path, is so, I want to give it a new path.
I've attached an image explaining the situation and the desired result on each case.
your help is much appreciated. thank you!

Position of the first circle is described as
x1 = x1_0 + vx1 * t
y1 = y1_0 + vy1 * t
where x10 is initial x-coordinate, vx1 is x-component of velocity vector, t is time.
Make similar expression for the second circle center, build expression for squared distance and find time when squared distance becomes equal to 4R^2 (for equal radii) - if solution exists at needed time interval, it is the moment of circles' collision.
In your designations (seems you have equal velocities):
RSum = circleA.radius + circleB.radius
//position changes
dax = (circleA.pathx - circleA.x)
day = (circleA.pathy - circleA.y)
//normalize components
lenA = Sqrt(dax * dax + day * day)
dax = dax / lenA
day = day / lenA
//position vs time
ax = circleA.x + dax * t
ay = circleA.y + day * t
and similar for B circle
Now make distance equation, substitute ax, bx, ay, by expressions and solve it for unknown t (quadratic equation, might have 0,1,2 roots)
(ax - bx) * (ax - bx) + (ay - by) * (ay - by) = RSum * RSum
or
(circleA.x + dax * t - circleB.x - dbx * t) * ....

Related

How to move point with shape's changing rotation and position

I have a web app, where I am drawing a triangle and also drawing points on top of it to show the vertices that it has. (fig 1 at 0 radians)
The circle and triangle rotate fine, its just the blue point that I cant seem to move appropriately. When I rotate the triangle (along with circle), the X and Y does not translate to either corners of the triangle besides the red dot. (fig 2 at .75 radians)
The shape as a whole is drawn with the following vertices for display points.
this.transform = ctx.getTransform();
this.boundPoints[0] = { //red point
x: (this.transform.a + this.x)+(this.radius)* Math.cos(this.rotation),
y: (this.transform.d + this.y)+(this.radius)* Math.sin(this.rotation)
}
this.boundPoints[1] = { //blue point
x: (this.transform.a + this.x)+(this.radius+ this.range)* Math.cos(this.rotation),
y: (this.transform.d + this.y)+(this.radius)* Math.sin(this.rotation)
}
What I want to have happen, is this
Where that point keeps its position relative to the triangle regardless of its position and rotation in the canvas. Without rotating, I can keep it there with its Y being
y: (this.transform.d + this.y+this.range)
but now I can't rotate or move the shape without the dot losing its placement. (Note: this.rotation is angle in radians)
My way of keeping track of all point of any shape is to create any array in my class that stores those values separate from the actual points that you are drawing to. I use those stored point mainly for collision detection with an odd shape that has been transformed/rotated/scaled.
Without your code it's hard to see how I would implement this technique but here's an example of a rotating triangle that you can scale and transform and the points are always tracked. This example also includes a commented out piece of code showing how to use the centroid to rotate from the center is needed.
this.position is the trasnlate
this.size is scale
this.r is rotate
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
canvas.width = 300;
canvas.height = 300;
let ptACopy, ptBCopy, ptCCopy;
class Triangle {
constructor(ptA, ptB, ptC) {
this.type = "tri";
this.ptA = ptACopy = ptA;
this.ptB = ptBCopy = ptB;
this.ptC = ptCCopy = ptC;
this.position = { x: 100, y: 100 }; //use this to position
this.size = { x: 2, y: 1 };
this.centroid = {
ox: (this.ptA.x + this.ptB.x + this.ptC.x) / 3,
oy: (this.ptA.y + this.ptB.y + this.ptC.y) / 3
};
this.c = "red";
this.a = 0;
this.r = this.a * (Math.PI / 180);
this.points = [];
for (let i = 0; i < 3; i++) {
this.points.push({ x: 0, y: 0 });
}
}
draw() {
//updates the points to counter the translating of the canvas to the centroid
//this is used to rotate from center if wanted
/*this.ptA = {
x: ptACopy.x - this.centroid.ox,
y: ptACopy.y - this.centroid.oy
};
this.ptB = {
x: ptBCopy.x - this.centroid.ox,
y: ptBCopy.y - this.centroid.oy
};
this.ptC = {
x: ptCCopy.x - this.centroid.ox,
y: ptCCopy.y - this.centroid.oy
};*/
let cos = Math.cos(this.r);
let sin = Math.sin(this.r);
ctx.save();
ctx.beginPath();
ctx.fillStyle = this.c;
ctx.setTransform(cos * this.size.x, sin * this.size.x, -sin * this.size.y, cos * this.size.y, this.position.x, this.position.y);
ctx.moveTo(this.ptA.x, this.ptA.y);
ctx.lineTo(this.ptB.x, this.ptB.y);
ctx.lineTo(this.ptC.x, this.ptC.y);
ctx.lineTo(this.ptA.x, this.ptA.y);
ctx.fill();
ctx.closePath();
ctx.restore();
}
updateCorners() {
this.a += 0.1;
this.r = this.a * (Math.PI / 180);
let cos = Math.cos(this.r);
let sin = Math.sin(this.r);
this.points[0].x =
this.ptA.x * this.size.x * cos -
this.ptA.y * this.size.y * sin +
this.position.x;
this.points[0].y =
this.ptA.x * this.size.x * sin +
this.ptA.y * this.size.y * cos +
this.position.y;
this.points[1].x =
this.ptB.x * this.size.x * cos -
this.ptB.y * this.size.y * sin +
this.position.x;
this.points[1].y =
this.ptB.x * this.size.x * sin +
this.ptB.y * this.size.y * cos +
this.position.y;
this.points[2].x =
this.ptC.x * this.size.x * cos -
this.ptC.y * this.size.y * sin +
this.position.x;
this.points[2].y =
this.ptC.x * this.size.x * sin +
this.ptC.y * this.size.y * cos +
this.position.y;
}
drawPoints() {
ctx.fillStyle = "blue";
this.points.map((x) => {
ctx.beginPath();
ctx.arc(x.x, x.y, 3, 0, Math.PI * 2);
ctx.fill();
});
}
}
let triangle = new Triangle(
{ x: 10, y: 20 },
{ x: 50, y: 60 },
{ x: 30, y: 100 }
);
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
triangle.draw();
triangle.updateCorners();
triangle.drawPoints();
requestAnimationFrame(animate);
}
animate();
<canvas id="canvas"></canvas>
To clarify some things in the code:
The purpose of using the following code is to ensure the shape is accurately drawn when translating it.
this.ptA = {
x: ptACopy.x - this.centroid.ox,
y: ptACopy.y - this.centroid.oy
};
If is were to not make a copy of the points and try to do
this.ptA = {
x: ptA.x - this.centroid.ox,
y: ptA.y - this.centroid.oy
};
then I would just get undefined because I'm trying to use ptA to calculate ptA.
Also when creating the triangle if I wanted ptA to be at (0,0) then I could set it there and then use the above function to offset the triangle for rotation purposes. example using that to have it rotate around ptA with a 20px radius:
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
canvas.width = 300;
canvas.height = 300;
let ptACopy, ptBCopy, ptCCopy;
class Triangle {
constructor(ptA, ptB, ptC) {
this.type = "tri";
this.ptA = ptACopy = ptA;
this.ptB = ptBCopy = ptB;
this.ptC = ptCCopy = ptC;
this.position = { x: 100, y: 100 }; //use this to position
this.size = { x: 1, y: 1 };
this.centroid = {
ox: (this.ptA.x + this.ptB.x + this.ptC.x) / 3,
oy: (this.ptA.y + this.ptB.y + this.ptC.y) / 3
};
this.c = "red";
this.a = 0;
this.r = this.a * (Math.PI / 180);
this.points = [];
for (let i = 0; i < 3; i++) {
this.points.push({ x: 0, y: 0 });
}
}
draw() {
//updates the points to counter the translating of the canvas to the centroid
this.ptA = {
x: ptACopy.x + 20,
y: ptACopy.y + 20
};
this.ptB = {
x: ptBCopy.x + 20,
y: ptBCopy.y + 20
};
this.ptC = {
x: ptCCopy.x + 20,
y: ptCCopy.y + 20
};
let cos = Math.cos(this.r);
let sin = Math.sin(this.r);
ctx.save();
ctx.beginPath();
ctx.fillStyle = this.c;
ctx.setTransform(cos * this.size.x, sin * this.size.x, -sin * this.size.y, cos * this.size.y, this.position.x, this.position.y);
ctx.moveTo(this.ptA.x, this.ptA.y);
ctx.lineTo(this.ptB.x, this.ptB.y);
ctx.lineTo(this.ptC.x, this.ptC.y);
ctx.lineTo(this.ptA.x, this.ptA.y);
ctx.fill();
ctx.closePath();
ctx.fillStyle = 'rgba(0,0,0,0.2)';
ctx.fillRect(0,0,canvas.width, canvas.height);
ctx.restore();
}
updateCorners() {
this.a += 0.5;
this.r = this.a * (Math.PI / 180);
let cos = Math.cos(this.r);
let sin = Math.sin(this.r);
this.points[0].x =
this.ptA.x * this.size.x * cos -
this.ptA.y * this.size.y * sin +
this.position.x;
this.points[0].y =
this.ptA.x * this.size.x * sin +
this.ptA.y * this.size.y * cos +
this.position.y;
this.points[1].x =
this.ptB.x * this.size.x * cos -
this.ptB.y * this.size.y * sin +
this.position.x;
this.points[1].y =
this.ptB.x * this.size.x * sin +
this.ptB.y * this.size.y * cos +
this.position.y;
this.points[2].x =
this.ptC.x * this.size.x * cos -
this.ptC.y * this.size.y * sin +
this.position.x;
this.points[2].y =
this.ptC.x * this.size.x * sin +
this.ptC.y * this.size.y * cos +
this.position.y;
}
drawPoints() {
ctx.fillStyle = "blue";
this.points.map((x) => {
ctx.beginPath();
ctx.arc(x.x, x.y, 3, 0, Math.PI * 2);
ctx.fill();
});
}
}
let triangle = new Triangle(
{ x: 0, y: 0 },
{ x: 50, y: 60 },
{ x: 30, y: 100 }
);
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
triangle.draw();
triangle.updateCorners();
triangle.drawPoints();
requestAnimationFrame(animate);
}
animate();
<canvas id="canvas"></canvas>
I gave the canvas a background for better visualization.
UPDATE:
I am adding an example using getTransform() which returns the transformation matrix.
We can then use those values to calculate each point by passing them to a function. This shortens the code slightly inside the class and makes things look cleaner IMO.
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
canvas.width = 400;
canvas.height = 400;
let t;
class Rect {
constructor(x, y, w, h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.scale = {x: 1, y: 1}
this.cx = this.x + this.w / 2;
this.cy = this.y + this.h / 2;
this.color = "red";
this.angle = 0;
this.rotation = (this.angle * Math.PI) / 180;
this.pts = []
}
draw() {
this.angle += 0.5;
this.rotation = (this.angle * Math.PI) / 180;
const cos = Math.cos(this.rotation)
const sin = Math.sin(this.rotation)
ctx.save();
ctx.setTransform(cos * this.scale.x, sin * this.scale.x, -sin * this.scale.y, cos * this.scale.y, this.x, this.y);
t = ctx.getTransform();
ctx.fillStyle = this.color;
ctx.fillRect(-this.w / 2, -this.h / 2, this.w, this.h);
ctx.restore();
}
drawVertices() {
for (let i=0; i < this.pts.length; i++) {
ctx.beginPath();
ctx.fillStyle = "blue";
ctx.arc(this.pts[i].x, this.pts[i].y, 3, 0, Math.PI * 2);
ctx.fill();
ctx.closePath();
}
}
updateVertices() {
this.pts[0] = calcVertices(t['a'], t['b'], t['c'], t['d'], t['e'], t['f'], 0, 0, this.cx, this.cy)//top left width and height are passed as 0.
this.pts[1] = calcVertices(t['a'], t['b'], t['c'], t['d'], t['e'], t['f'], this.w, 0, this.cx, this.cy) //top right only passes width. Height is 0.
this.pts[2] = calcVertices(t['a'], t['b'], t['c'], t['d'], t['e'], t['f'], this.w, this.h, this.cx, this.cy) //bottom right passes both wodth and height.
this.pts[3] = calcVertices(t['a'], t['b'], t['c'], t['d'], t['e'], t['f'], 0, this.h, this.cx, this.cy)//bottom left only passes height. Width is 0.
}
}
let rect1 = new Rect(100, 100, 50, 75);
let rect2 = new Rect(250, 150, 100, 25);
function calcVertices(a, b, c, d, e, f, w, h, cx, cy) {
let x, y;
x = (e + w - cx) * a + (f + h - cy) * c + (e);
y = (e + w - cx) * b + (f + h - cy) * d + (f);
return {x: x, y: y}
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
rect1.draw();
rect1.updateVertices();
rect1.drawVertices();
rect2.draw();
rect2.updateVertices();
rect2.drawVertices();
requestAnimationFrame(animate);
}
animate();
<canvas id="canvas"></canvas>
I will answer with complex numbers for convenience, but every complex expression can be rewritten with reals only.
You did not specify the rotation center (presumably the origin) and for generality I will assume the point c. To rotate any point p around this center, we apply the equation
p' = r.(p - c) + c
where r = cos Θ + i sin Θ implements a rotation by angle Θ.
Now to rotate any shape, assuming that the shape has a reference point (say its center or some other remarkable point such as a corner), you need to apply the rotation to this reference point, and assign the angle Θ to the shape (if the shape already had an angle τ assigned to it, the new angle is τ + Θ.)
If you also want to rescale the shape, use r = s (cos Θ + i sin Θ) where s is the desired scaling factor and apply this transformation to the reference point. Also apply the factor s to all dimension parameters of the shapes (or t . s is the parameters already had a factor t applied.)

html canvas check that object is in angle

I have a circle, and a object.
I want to draw a circle segment with specified spread, and next check that the object is in defined angle, if it is, angle color will be red, otherwise green. But my code does not work in some cases...
in this case it work:
in this too:
but here it isn't:
I know that my angle detection code part is not perfect, but I have no idea what I can do.
This is my code:
html:
<html>
<head></head>
<body>
<canvas id="c" width="800" height="480" style="background-color: #DDD"></canvas>
<script src="script.js"></script>
</body>
</html>
js:
window.addEventListener('mousemove', updateMousePos, false);
var canvas = document.getElementById("c");
var context = canvas.getContext("2d");
//mouse coordinates
var mx = 0, my = 0;
draw();
function draw()
{
context.clearRect(0, 0, canvas.width, canvas.height);
//object coordinates
var ox = 350, oy = 260;
context.beginPath();
context.arc(ox,oy,5,0,2*Math.PI);
context.fill();
//circle
var cx = 400, cy = 280;
var r = 100;
var segmentPoints = 20;
var circlePoints = 40;
var spread = Math.PI / 2;
var mouseAngle = Math.atan2(my - cy, mx - cx); //get angle between circle center and mouse position
context.beginPath();
context.strokeStyle = "blue";
context.moveTo(cx + r, cy);
for(var i=0; i<circlePoints; i++)
{
var a = 2 * Math.PI / (circlePoints - 1) * i;
var x = cx + Math.cos(a) * r;
var y = cy + Math.sin(a) * r;
context.lineTo(x, y);
}
context.lineTo(cx + r, cy);
context.stroke();
var objAngle = Math.atan2(oy - cy, ox - cx);
var lowerBorder = mouseAngle - spread / 2;
var biggerBorder = mouseAngle + spread / 2;
/////////////////////////////////////////////ANGLES DETECTION PART
if(objAngle >= lowerBorder && objAngle <= biggerBorder ||
objAngle <= biggerBorder && objAngle >= lowerBorder)
{
context.strokeStyle = "red";
}
else
context.strokeStyle = "green";
context.lineWidth = 3;
//angle center line
context.beginPath();
context.moveTo(cx, cy);
context.lineTo(cx + Math.cos(mouseAngle) * r * 2, cy + Math.sin(mouseAngle) * r * 2);
context.stroke();
//draw spread arc
context.beginPath();
context.moveTo(cx, cy);
for(var i=0; i<segmentPoints; i++)
{
var a = mouseAngle - spread / 2 + spread / (segmentPoints - 1) * i;
var x = cx + Math.cos(a) * r;
var y = cy + Math.sin(a) * r;
context.lineTo(x, y);
}
context.lineTo(cx, cy);
context.stroke();
//show degrees
context.font = "20px Arial";
context.fillText((lowerBorder * 180 / Math.PI).toFixed(2), Math.cos(lowerBorder) * r + cx, Math.sin(lowerBorder) * r + cy);
context.fillText((biggerBorder * 180 / Math.PI).toFixed(2), Math.cos(biggerBorder) * r + cx, Math.sin(biggerBorder) * r + cy);
context.fillText((mouseAngle * 180 / Math.PI).toFixed(2), Math.cos(mouseAngle) * r + cx, Math.sin(mouseAngle) * r + cy);
//update
setTimeout(function() { draw(); }, 10);
}
//getting mouse coordinates
function updateMousePos(evt)
{
var rect = document.getElementById("c").getBoundingClientRect();
mx = evt.clientX - rect.left;
my = evt.clientY - rect.top;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
position: absolute;
margin: auto;
left: 0;
right: 0;
border: solid 1px white;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
// Rotation here is being measured in Radians
// Given two 2D vectors A & B, the angle between them can be drawn from this formula
// A dot B = length(a) * length(b) * cos(angle)
// if the vectors are normalized (the length is 1) the formula becomes
// A dot B = cos(angle)
// angle = acos(a.x * b.x + a.y * b.y)
// So here you are concerned with the direction of the two vectors
// One will be the vector facing outward from the middle of your arc segment
// The other will be a directional vector from the point you want to do collision with to the center
// of the circle
var canvasWidth = 180;
var canvasHeight = 160;
var canvas = null;
var ctx = null;
var bounds = {top: 0.0, left: 0.0};
var circle = {
x: (canvasWidth * 0.5)|0,
y: (canvasHeight * 0.5)|0,
radius: 50.0,
rotation: 0.0, // In Radians
arcSize: 1.0
};
var point = {
x: 0.0,
y: 0.0
};
window.onmousemove = function(e) {
point.x = e.clientX - bounds.left;
point.y = e.clientY - bounds.top;
}
// runs after the page has loaded
window.onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
bounds = canvas.getBoundingClientRect();
ctx = canvas.getContext("2d");
loop();
}
function loop() {
// Update Circle Rotation
circle.rotation = circle.rotation + 0.025;
if (circle.rotation > 2*Math.PI) {
circle.rotation = 0.0;
}
// Vector A (Point Pos -> Circle Pos)
var aX = circle.x - point.x;
var aY = circle.y - point.y;
var aLength = Math.sqrt(aX * aX + aY * aY);
// Vector B (The direction the middle of the arc is facing away from the circle)
var bX = Math.sin(circle.rotation);
var bY =-Math.cos(circle.rotation); // -1 is facing upward, not +1
var bLength = 1.0;
// Normalize vector A
aX = aX / aLength;
aY = aY / aLength;
// Are we inside the arc segment?
var isInsideRadius = aLength < circle.radius;
var isInsideAngle = Math.abs(Math.acos(aX * bX + aY * bY)) < circle.arcSize * 0.5;
var isInsideArc = isInsideRadius && isInsideAngle;
// Clear the screen
ctx.fillStyle = "gray";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
// Draw the arc
ctx.strokeStyle = isInsideArc ? "green" : "black";
ctx.beginPath();
ctx.moveTo(circle.x,circle.y);
ctx.arc(
circle.x,
circle.y,
circle.radius,
circle.rotation - circle.arcSize * 0.5 + Math.PI * 0.5,
circle.rotation + circle.arcSize * 0.5 + Math.PI * 0.5,
false
);
ctx.lineTo(circle.x,circle.y);
ctx.stroke();
// Draw the point
ctx.strokeStyle = "black";
ctx.fillStyle = "darkred";
ctx.beginPath();
ctx.arc(
point.x,
point.y,
5.0,
0.0,
2*Math.PI,
false
);
ctx.fill();
ctx.stroke();
// This is better to use then setTimeout()
// It automatically syncs the loop to 60 fps for you
requestAnimationFrame(loop);
}
</script>
</body>
</html>

Can't get Three.js onDocumentMouseDown to work correctly

I've looked at a lot of examples -- and borrowed from some -- and can't seem to get this to work right. What I want is for the raycaster in onDocumentMouseDown to pick up sprites when the user clicks anywhere on the visible surface of a sprite. What I'm getting is a misaligned result, in that a sprite may be picked up if the user clicks somewhat to the right, above, or below the sprite, and will not pick it up at all if the user clicks on the left edge of the sprite. So basically something is misaligned, and I am at a loss for figuring out what I am doing wrong. Any guidance would be appreciated.
<script src="/common/three.js"></script>
<script src="/common/Detector.js"></script>
<script src="/common/CanvasRenderer.js"></script>
<script src="/common/GeometryUtils.js"></script>
<script src="/common/OrbitControls.js"></script>
<div id="WebGLCanvas"></div>
<script>
var container, scene, camera, renderer, controls;
var keyboard;
</script>
<script>
// custom global variables
var mouse = { x: 0, y: 0 };
var raycaster;
var sprites = new Array();
init();
try {
for (i = 0; i < 10; i++) {
var text = "Text " + i;
var x = Math.random() * 100;
var y = Math.random() * 100;
var z = Math.random() * 100;
var spritey = addOrUPdateSprite(text, i, x, y, z);
}
}
catch (ex) {
alert("error when creating sprite: " + ex.message);
}
animate();
function init() {
try {
scene = new THREE.Scene();
// CAMERA
var cont = document.getElementById("WebGLCanvas");
var SCREEN_WIDTH = window.innerWidth;
OFFSET_TOP = document.getElementById("WebGLCanvas").getBoundingClientRect().top;
var SCREEN_HEIGHT = window.innerHeight - OFFSET_TOP; //; //-document.getElementById("upper").clientHeight;
var VIEW_ANGLE = 60;
var ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT;
var NEAR = 0.1;
var FAR = 1000;
camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
scene.add(camera);
camera.position.set(0, 100, 200);
camera.lookAt(new THREE.Vector3());
renderer = new THREE.WebGLRenderer({ antialias: true });
container = document.getElementById('WebGLCanvas');
container.appendChild(renderer.domElement);
renderer.setSize(window.innerWidth, SCREEN_HEIGHT);
controls = new THREE.OrbitControls(camera, renderer.domElement);
// spritey.position.normalize();
raycaster = new THREE.Raycaster();
document.addEventListener('mousedown', onDocumentMouseDown, false);
document.addEventListener('touchstart', onDocumentTouchStart, false);
}
catch (ex) {
alert("error " + ex.message);
}
}
function animate() {
requestAnimationFrame(animate);
render();
update();
}
function update() {
controls.update();
}
function render() {
renderer.render(scene, camera);
}
function addOrUPdateSprite(text, name, x, y, z) {
var sprite = scene.getObjectByName(name);
if (sprite == null) {
sprite = makeTextSprite(text, { fontsize: 36, borderColor: { r: 255, g: 0, b: 0, a: 1.0 }, backgroundColor: { r: 255, g: 100, b: 100, a: 0.8 } });
sprite.name = name;
sprites.push(sprite);
scene.add(sprite);
}
sprite.position.set(x, y, z);
}
function makeTextSprite(message, parameters) {
if (parameters === undefined) parameters = {};
var fontface = parameters.hasOwnProperty("fontface") ? parameters["fontface"] : "sans-serif";
var fontsize = parameters.hasOwnProperty("fontsize") ? parameters["fontsize"] : 36;
var borderThickness = parameters.hasOwnProperty("borderThickness") ? parameters["borderThickness"] : 1;
var borderColor = parameters.hasOwnProperty("borderColor") ? parameters["borderColor"] : { r: 0, g: 0, b: 0, a: 1.0 };
var backgroundColor = parameters.hasOwnProperty("backgroundColor") ? parameters["backgroundColor"] : { r: 255, g: 255, b: 255, a: 1.0 };
var textColor = parameters.hasOwnProperty("textColor") ? parameters["textColor"] : { r: 0, g: 0, b: 0, a: 1.0 };
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.font = fontsize + "px " + fontface;
var metrics = context.measureText(message);
var textWidth = metrics.width;
context.fillStyle = "rgba(" + backgroundColor.r + "," + backgroundColor.g + "," + backgroundColor.b + "," + backgroundColor.a + ")";
context.strokeStyle = "rgba(" + borderColor.r + "," + borderColor.g + "," + borderColor.b + "," + borderColor.a + ")";
context.lineWidth = borderThickness;
roundRect(context, borderThickness / 2, borderThickness / 2, (textWidth + borderThickness) * 1.1, fontsize * 1.4 + borderThickness, 8);
context.fillStyle = "rgba(" + textColor.r + ", " + textColor.g + ", " + textColor.b + ", 1.0)";
context.fillText(message, borderThickness, fontsize + borderThickness);
var texture = new THREE.Texture(canvas)
texture.needsUpdate = true;
var spriteMaterial = new THREE.SpriteMaterial({ map: texture, useScreenCoordinates: false });
var sprite = new THREE.Sprite(spriteMaterial);
sprite.scale.set(1.0 * fontsize, 0.5 * fontsize, 1.5 * fontsize);
return sprite;
}
// function for drawing rounded rectangles
function roundRect(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
ctx.lineTo(x + w, y + h - r);
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
ctx.lineTo(x + r, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
function onDocumentTouchStart(event) {
event.preventDefault();
event.clientX = event.touches[0].clientX;
event.clientY = event.touches[0].clientY;
onDocumentMouseDown(event);
}
function onDocumentMouseDown(event) {
mouse.x = (event.clientX / renderer.domElement.clientWidth) * 2 - 1;
mouse.y = -((event.clientY) / renderer.domElement.clientHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(sprites, true);
if (intersects.length > 0) {
var obj = intersects[0].object;
alert(obj.name);
event.preventDefault();
}
}
</script>
In your makeTextSprite() function, after
var textWidth = metrics.width;
add this
context.strokeStyle = "white";
context.lineWidth = 5;
context.strokeRect(0,0,canvas.width, canvas.height);
and you will see, that your sprites have not the size you think of.
UPD. You can set the size of a canvas like this
var ctxFont = "bold " + fontsize + "px " + fontface;
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.font = ctxFont;
var metrics = context.measureText(message);
var textWidth = metrics.width;
canvas.width = textWidth + borderThickness * 2;
canvas.height = fontsize * 1.2 + (borderThickness * 2);
context = canvas.getContext('2d');
context.font = ctxFont;
and then set the scale of a sprite
sprite.scale.set(canvas.width / 10, canvas.height / 10, 1);
jsfiddle example
Your Three.js canvas probably isn't at the top left of the screen, and you're not taking into account the offset from 0,0 on the page. To fix it, adjust the mouse position to subtract the offset.
var rect = container.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / renderer.domElement.clientWidth) * 2 - 1;
mouse.y = -((event.clientY - rect.top) / renderer.domElement.clientHeight) * 2 + 1;

Javascript Canvas apply Radial Gradient to Segment?

I am trying to create a shadow system for my 2D Game in a HTML5 Canvas. Right now, I am rendering my shadows like so:
function drawShadows(x, y, width) {
if (shadowSprite == null) {
shadowSprite = document.createElement('canvas');
var tmpCtx = shadowSprite.getContext('2d');
var shadowBlur = 20;
shadowSprite.width = shadowResolution;
shadowSprite.height = shadowResolution;
var grd = tmpCtx.createLinearGradient(-(shadowResolution / 4), 0,
shadowResolution, 0);
grd.addColorStop(0, "rgba(0, 0, 0, 0.1)");
grd.addColorStop(1, "rgba(0, 0, 0, 0)");
tmpCtx.fillStyle = grd;
tmpCtx.shadowBlur = shadowBlur;
tmpCtx.shadowColor = "#000";
tmpCtx.fillRect(0, 0, shadowResolution, shadowResolution);
}
graph.save();
graph.rotate(sun.getDir(x, y));
graph.drawImage(shadowSprite, 0, -(width / 2), sun.getDist(x, y), width);
graph.restore();
}
This renders a cube with a linear gradient that fades from black to alpha 0.
This however does not produce a realistic result, since it will always be a rectangle. Here is an illustration to describe the problem:
Sorry i'm not very artistic. It would not be an issue to draw the trapezoid shape. (Seen in blue). The issue is that I still there to be a gradient. Is it possible to draw a shape like that with a gradient?
The canvas is very flexible. Almost anything is possible. This example draws the light being cast. But it can just as easily be the reverse. Draw the shadows as a gradient.
If you are after realism then instead of rendering a gradient for the lighting (or shadows) use the shape created to set a clipping area and then render a accurate lighting and shadow solution.
With lineTo and gradients you can create any shape and gradient you my wish. Also to get the best results use globalCompositeOperation as they have a large variety of filters.
The demo just shows how to mix a gradient and a shadow map. (Very basic no recursion implemented, and shadows are just approximations.)
var canvas = document.getElementById("canV");
var ctx = canvas.getContext("2d");
var mouse = {
x:0,
y:0,
};
function mouseMove(event){
mouse.x = event.offsetX; mouse.y = event.offsetY;
if(mouse.x === undefined){ mouse.x = event.clientX; mouse.y = event.clientY;}
}
// add mouse controls
canvas.addEventListener('mousemove',mouseMove);
var boundSize = 10000; // a number....
var createImage = function(w,h){ // create an image
var image;
image = document.createElement("canvas");
image.width = w;
image.height = h;
image.ctx = image.getContext("2d");
return image;
}
var directionC = function(x,y,xx,yy){ // this should be inLine but the angles were messing with my head
var a; // so moved it out here
a = Math.atan2(yy - y, xx - x); // for clarity and the health of my sanity
return (a + Math.PI * 2) % (Math.PI * 2); // Dont like negative angles.
}
// Create background image
var back = createImage(20, 20);
back.ctx.fillStyle = "#333";
back.ctx.fillRect(0, 0, 20, 20);
// Create background image
var backLight = createImage(20, 20);
backLight .ctx.fillStyle = "#ACD";
backLight .ctx.fillRect(0, 0, 20, 20);
// create circle image
var circle = createImage(64, 64);
circle.ctx.fillStyle = "red";
circle.ctx.beginPath();
circle.ctx.arc(32, 32, 30, 0, Math.PI * 2);
circle.ctx.fill();
// create some circles semi random
var circles = [];
circles.push({
x : 200 * Math.random(),
y : 200 * Math.random(),
scale : Math.random() * 0.8 + 0.3,
});
circles.push({
x : 200 * Math.random() + 200,
y : 200 * Math.random(),
scale : Math.random() * 0.8 + 0.3,
});
circles.push({
x : 200 * Math.random() + 200,
y : 200 * Math.random() + 200,
scale : Math.random() * 0.8 + 0.3,
});
circles.push({
x : 200 * Math.random(),
y : 200 * Math.random() + 200,
scale : Math.random() * 0.8 + 0.3,
});
// shadows on for each circle;
var shadows = [{},{},{},{}];
var update = function(){
var c, dir, dist, x, y, x1, y1, x2, y2, dir1, dir2, aAdd, i, j, s, s1 ,nextDir, rev, revId;
rev = false; // if inside a circle reverse the rendering.
// set up the gradient at the mouse pos
var g = ctx.createRadialGradient(mouse.x, mouse.y, canvas.width * 1.6, mouse.x, mouse.y, 2);
// do each circle and work out the two shadow lines coming from it.
for(var i = 0; i < circles.length; i++){
c = circles[i];
dir = directionC(mouse.x, mouse.y, c.x, c.y);
dist = Math.hypot(mouse.x - c.x, mouse.y - c.y);
// cludge factor. Could not be bother with the math as the light sourse nears an object
if(dist < 30* c.scale){
rev = true;
revId = i;
}
aAdd = (Math.PI / 2) * (0.5 / (dist - 30 * c.scale));
x1 = Math.cos(dir - (Math.PI / 2 + aAdd)) * 30 * c.scale;
y1 = Math.sin(dir - (Math.PI / 2 + aAdd)) * 30 * c.scale;
x2 = Math.cos(dir + (Math.PI / 2 + aAdd)) * 30 * c.scale;
y2 = Math.sin(dir + (Math.PI / 2 + aAdd)) * 30 * c.scale;
// direction of both shadow lines
dir1 = directionC(mouse.x, mouse.y, c.x + x1, c.y + y1);
dir2 = directionC(mouse.x, mouse.y, c.x + x2, c.y + y2);
// create the shadow object to hold details
shadows[i].dir = dir;
shadows[i].d1 = dir1;
if (dir2 < dir1) { // make sure second line is always greater
dir2 += Math.PI * 2;
}
shadows[i].d2 = dir2;
shadows[i].x1 = (c.x + x1); // set the shadow start pos
shadows[i].y1 = (c.y + y1);
shadows[i].x2 = (c.x + x2); // for both lines
shadows[i].y2 = (c.y + y2);
shadows[i].circle = c; // ref the circle
shadows[i].dist = dist; // set dist from light
shadows[i].branch1 = undefined; //.A very basic tree for shadows that interspet other object
shadows[i].branch2 = undefined; //
shadows[i].branch1Dist = undefined;
shadows[i].branch2Dist = undefined;
shadows[i].active = true; // false if the shadow is in a shadow
shadows[i].id = i;
}
shadows.sort(function(a,b){ // sort by distance from light
return a.dist - b.dist;
});
// cull shdows with in shadows and connect circles with joined shadows
for(i = 0; i < shadows.length; i++){
s = shadows[i];
for(j = i + 1; j < shadows.length; j++){
s1 = shadows[j];
if(s1.d1 > s.d1 && s1.d2 < s.d2){ // if shadow in side another
s1.active = false; // cull it
}else
if(s.d1 > s1.d1 && s.d1 < s1.d2){ // if shodow intercepts going twards light
s1.branch1 = s;
s.branch1Dist = s1.dist - s.dist;
s.active = false;
}else
if(s.d2 > s1.d1 && s.d2 < s1.d2){ // away from light
s.branch2 = s1;
s.branch2Dist = s1.dist - s.dist;
s1.active = false;
}
}
}
// keep it quick so not using filter
// filter culled shadows
var shadowsShort = [];
for (i = 0; i < shadows.length; i++) {
if ((shadows[i].active && !rev) || (rev && shadows[i].id === revId)) { // to much hard work makeng shadow from inside the circles. Was a good idea at the time. But this i just an example after all;
shadowsShort.push(shadows[i])
}
}
// sort shadows in clock wise render order
if(rev){
g.addColorStop(0.3, "rgba(210,210,210,0)");
g.addColorStop(0.6, "rgba(128,128,128,0.5)");
g.addColorStop(1, "rgba(0,0,0,0.9)");
shadowsShort.sort(function(a,b){
return b.dir - a.dir;
});
// clear by drawing background image.
ctx.drawImage(backLight, 0, 0, canvas.width, canvas.height);
}else{
g.addColorStop(0.3, "rgba(0,0,0,0)");
g.addColorStop(0.6, "rgba(128,128,128,0.5)");
g.addColorStop(1, "rgba(215,215,215,0.9)");
shadowsShort.sort(function(a,b){
return a.dir - b.dir;
});
// clear by drawing background image.
ctx.drawImage(back, 0, 0, canvas.width, canvas.height);
}
// begin drawin the light area
ctx.fillStyle = g; // set the gradient as the light
ctx.beginPath();
for(i = 0; i < shadowsShort.length; i++){ // for each shadow move in to the light across the circle and then back out away from the light
s = shadowsShort[i];
x = s.x1 + Math.cos(s.d1) * boundSize;
y = s.y1 + Math.sin(s.d1) * boundSize;
if (i === 0) { // if the start move to..
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
ctx.lineTo(s.x1, s.y1);
if (s.branch1 !== undefined) { // if braching. (NOTE this is not recursive. the correct solution would to math this a function and use recursion to climb in an out)
s = s.branch1;
x = s.x1 + Math.cos(s.d1) * s.branch1Dist;
y = s.y1 + Math.sin(s.d1) * s.branch1Dist;
ctx.lineTo(x, y);
ctx.lineTo(s.x1, s.y1);
}
ctx.lineTo(s.x2, s.y2);
if (s.branch2 !== undefined) {
x = s.x2 + Math.cos(s.d2) * s.branch2Dist;
y = s.y2 + Math.sin(s.d2) * s.branch2Dist;
ctx.lineTo(x, y);
s = s.branch2;
ctx.lineTo(s.x2, s.y2);
}
x = s.x2 + Math.cos(s.d2) * boundSize;
y = s.y2 + Math.sin(s.d2) * boundSize;
ctx.lineTo(x, y);
// now fill in the light between shadows
s1 = shadowsShort[(i + 1) % shadowsShort.length];
nextDir = s1.d1;
if(rev){
if (nextDir > s.d2) {
nextDir -= Math.PI * 2
}
}else{
if (nextDir < s.d2) {
nextDir += Math.PI * 2
}
}
x = Math.cos((nextDir+s.d2)/2) * boundSize + canvas.width / 2;
y = Math.sin((nextDir+s.d2)/2) * boundSize + canvas.height / 2;
ctx.lineTo(x, y);
}
// close the path.
ctx.closePath();
// set the comp to lighten or multiply
if(rev){
ctx.globalCompositeOperation ="multiply";
}else{
ctx.globalCompositeOperation ="lighter";
}
// draw the gradient
ctx.fill()
ctx.globalCompositeOperation ="source-over";
// draw the circles
for (i = 0; i < circles.length; i++) {
c = circles[i];
ctx.drawImage(circle, c.x - 32 * c.scale, c.y - 32 * c.scale, 64 * c.scale, 64 * c.scale);
}
// feed the herbervors.
window.requestAnimationFrame(update);
}
update();
.canC { width:400px; height:400px;}
<canvas class="canC" id="canV" width=400 height=400></canvas>

How Can I draw a Text Along arc path with HTML 5 Canvas?

I want to draw a canvas graphic like this flash animation:
http://www.cci.com.tr/tr/bizi-taniyin/tarihcemiz/
I drew six arcs and I want to write six words in these arcs. Any ideas?
I have a jsFiddle to apply text to any arbitrary Bezier curve definition. Enjoy http://jsfiddle.net/Makallus/hyyvpp8g/
var first = true;
startIt();
function startIt() {
canvasDiv = document.getElementById('canvasDiv');
canvasDiv.innerHTML = '<canvas id="layer0" width="300" height="300"></canvas>'; //for IE
canvas = document.getElementById('layer0');
ctx = canvas.getContext('2d');
ctx.fillStyle = "black";
ctx.font = "18px arial black";
curve = document.getElementById('curve');
curveText = document.getElementById('text');
$(curve).keyup(function(e) {
changeCurve();
});
$(curveText).keyup(function(e) {
changeCurve();
});
if (first) {
changeCurve();
first = false;
}
}
function changeCurve() {
points = curve.value.split(',');
if (points.length == 8) drawStack();
}
function drawStack() {
Ribbon = {
maxChar: 50,
startX: points[0],
startY: points[1],
control1X: points[2],
control1Y: points[3],
control2X: points[4],
control2Y: points[5],
endX: points[6],
endY: points[7]
};
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.beginPath();
ctx.moveTo(Ribbon.startX, Ribbon.startY);
ctx.bezierCurveTo(Ribbon.control1X, Ribbon.control1Y,
Ribbon.control2X, Ribbon.control2Y,
Ribbon.endX, Ribbon.endY);
ctx.stroke();
ctx.restore();
FillRibbon(curveText.value, Ribbon);
}
function FillRibbon(text, Ribbon) {
var textCurve = [];
var ribbon = text.substring(0, Ribbon.maxChar);
var curveSample = 1000;
xDist = 0;
var i = 0;
for (i = 0; i < curveSample; i++) {
a = new bezier2(i / curveSample, Ribbon.startX, Ribbon.startY, Ribbon.control1X, Ribbon.control1Y, Ribbon.control2X, Ribbon.control2Y, Ribbon.endX, Ribbon.endY);
b = new bezier2((i + 1) / curveSample, Ribbon.startX, Ribbon.startY, Ribbon.control1X, Ribbon.control1Y, Ribbon.control2X, Ribbon.control2Y, Ribbon.endX, Ribbon.endY);
c = new bezier(a, b);
textCurve.push({
bezier: a,
curve: c.curve
});
}
letterPadding = ctx.measureText(" ").width / 4;
w = ribbon.length;
ww = Math.round(ctx.measureText(ribbon).width);
totalPadding = (w - 1) * letterPadding;
totalLength = ww + totalPadding;
p = 0;
cDist = textCurve[curveSample - 1].curve.cDist;
z = (cDist / 2) - (totalLength / 2);
for (i = 0; i < curveSample; i++) {
if (textCurve[i].curve.cDist >= z) {
p = i;
break;
}
}
for (i = 0; i < w; i++) {
ctx.save();
ctx.translate(textCurve[p].bezier.point.x, textCurve[p].bezier.point.y);
ctx.rotate(textCurve[p].curve.rad);
ctx.fillText(ribbon[i], 0, 0);
ctx.restore();
x1 = ctx.measureText(ribbon[i]).width + letterPadding;
x2 = 0;
for (j = p; j < curveSample; j++) {
x2 = x2 + textCurve[j].curve.dist;
if (x2 >= x1) {
p = j;
break;
}
}
}
} //end FillRibon
function bezier(b1, b2) {
//Final stage which takes p, p+1 and calculates the rotation, distance on the path and accumulates the total distance
this.rad = Math.atan(b1.point.mY / b1.point.mX);
this.b2 = b2;
this.b1 = b1;
dx = (b2.x - b1.x);
dx2 = (b2.x - b1.x) * (b2.x - b1.x);
this.dist = Math.sqrt(((b2.x - b1.x) * (b2.x - b1.x)) + ((b2.y - b1.y) * (b2.y - b1.y)));
xDist = xDist + this.dist;
this.curve = {
rad: this.rad,
dist: this.dist,
cDist: xDist
};
}
function bezierT(t, startX, startY, control1X, control1Y, control2X, control2Y, endX, endY) {
//calculates the tangent line to a point in the curve; later used to calculate the degrees of rotation at this point.
this.mx = (3 * (1 - t) * (1 - t) * (control1X - startX)) + ((6 * (1 - t) * t) * (control2X - control1X)) + (3 * t * t * (endX - control2X));
this.my = (3 * (1 - t) * (1 - t) * (control1Y - startY)) + ((6 * (1 - t) * t) * (control2Y - control1Y)) + (3 * t * t * (endY - control2Y));
}
function bezier2(t, startX, startY, control1X, control1Y, control2X, control2Y, endX, endY) {
//Quadratic bezier curve plotter
this.Bezier1 = new bezier1(t, startX, startY, control1X, control1Y, control2X, control2Y);
this.Bezier2 = new bezier1(t, control1X, control1Y, control2X, control2Y, endX, endY);
this.x = ((1 - t) * this.Bezier1.x) + (t * this.Bezier2.x);
this.y = ((1 - t) * this.Bezier1.y) + (t * this.Bezier2.y);
this.slope = new bezierT(t, startX, startY, control1X, control1Y, control2X, control2Y, endX, endY);
this.point = {
t: t,
x: this.x,
y: this.y,
mX: this.slope.mx,
mY: this.slope.my
};
}
function bezier1(t, startX, startY, control1X, control1Y, control2X, control2Y) {
//linear bezier curve plotter; used recursivly in the quadratic bezier curve calculation
this.x = ((1 - t) * (1 - t) * startX) + (2 * (1 - t) * t * control1X) + (t * t * control2X);
this.y = ((1 - t) * (1 - t) * startY) + (2 * (1 - t) * t * control1Y) + (t * t * control2Y);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<TR>
<TH>Bezier Curve</TH>
<TD>
<input size="80" type="text" id="curve" name="curve" value="99.2,177.2,130.02,60.0,300.5,276.2,300.7,176.2">
</TD>
</TR>
<TR>
<TH>Text</TH>
<TD>
<input size="80" type="text" id="text" name="text" value="testing 1234567890">
</TD>
</TR>
<TR>
<TD colspan=2>
<div id="canvasDiv"></div>
</TD>
</TR>
</table>
An old old question... nevertheless, on my blog, I take a fairly close look at creating circular text using HTML5 Canvas:
html5graphics.blogspot.com
In the example, options include rounded text alignment (left, center and right) from a given angle, inward and outward facing text, kerning (adjustable gap between characters) and text inside or outside the radius.
There is also a jsfiddle with a working example.
It is as follows:
document.body.appendChild(getCircularText("ROUNDED TEXT LOOKS BEST IN CAPS!", 250, 0, "center", true, true, "Arial", "18pt", 0));
function getCircularText(text, diameter, startAngle, align, textInside, inwardFacing, fName, fSize, kerning) {
// text: The text to be displayed in circular fashion
// diameter: The diameter of the circle around which the text will
// be displayed (inside or outside)
// startAngle: In degrees, Where the text will be shown. 0 degrees
// if the top of the circle
// align: Positions text to left right or center of startAngle
// textInside: true to show inside the diameter. False draws outside
// inwardFacing: true for base of text facing inward. false for outward
// fName: name of font family. Make sure it is loaded
// fSize: size of font family. Don't forget to include units
// kearning: 0 for normal gap between letters. positive or
// negative number to expand/compact gap in pixels
//------------------------------------------------------------------------
// declare and intialize canvas, reference, and useful variables
align = align.toLowerCase();
var mainCanvas = document.createElement('canvas');
var ctxRef = mainCanvas.getContext('2d');
var clockwise = align == "right" ? 1 : -1; // draw clockwise for aligned right. Else Anticlockwise
startAngle = startAngle * (Math.PI / 180); // convert to radians
// calculate height of the font. Many ways to do this
// you can replace with your own!
var div = document.createElement("div");
div.innerHTML = text;
div.style.position = 'absolute';
div.style.top = '-10000px';
div.style.left = '-10000px';
div.style.fontFamily = fName;
div.style.fontSize = fSize;
document.body.appendChild(div);
var textHeight = div.offsetHeight;
document.body.removeChild(div);
// in cases where we are drawing outside diameter,
// expand diameter to handle it
if (!textInside) diameter += textHeight * 2;
mainCanvas.width = diameter;
mainCanvas.height = diameter;
// omit next line for transparent background
mainCanvas.style.backgroundColor = 'lightgray';
ctxRef.font = fSize + ' ' + fName;
// Reverse letter order for align Left inward, align right outward
// and align center inward.
if (((["left", "center"].indexOf(align) > -1) && inwardFacing) || (align == "right" && !inwardFacing)) text = text.split("").reverse().join("");
// Setup letters and positioning
ctxRef.translate(diameter / 2, diameter / 2); // Move to center
startAngle += (Math.PI * !inwardFacing); // Rotate 180 if outward
ctxRef.textBaseline = 'middle'; // Ensure we draw in exact center
ctxRef.textAlign = 'center'; // Ensure we draw in exact center
// rotate 50% of total angle for center alignment
if (align == "center") {
for (var j = 0; j < text.length; j++) {
var charWid = ctxRef.measureText(text[j]).width;
startAngle += ((charWid + (j == text.length-1 ? 0 : kerning)) / (diameter / 2 - textHeight)) / 2 * -clockwise;
}
}
// Phew... now rotate into final start position
ctxRef.rotate(startAngle);
// Now for the fun bit: draw, rotate, and repeat
for (var j = 0; j < text.length; j++) {
var charWid = ctxRef.measureText(text[j]).width; // half letter
ctxRef.rotate((charWid/2) / (diameter / 2 - textHeight) * clockwise); // rotate half letter
// draw char at "top" if inward facing or "bottom" if outward
ctxRef.fillText(text[j], 0, (inwardFacing ? 1 : -1) * (0 - diameter / 2 + textHeight / 2));
ctxRef.rotate((charWid/2 + kerning) / (diameter / 2 - textHeight) * clockwise); // rotate half letter
}
// Return it
return (mainCanvas);
}
You can try the following code to see how to write text along an Arc Path using HTML5 Canvas
function drawTextAlongArc(context, str, centerX, centerY, radius, angle) {
var len = str.length,
s;
context.save();
context.translate(centerX, centerY);
context.rotate(-1 * angle / 2);
context.rotate(-1 * (angle / len) / 2);
for (var n = 0; n < len; n++) {
context.rotate(angle / len);
context.save();
context.translate(0, -1 * radius);
s = str[n];
context.fillText(s, 0, 0);
context.restore();
}
context.restore();
}
var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d'),
centerX = canvas.width / 2,
centerY = canvas.height - 30,
angle = Math.PI * 0.8,
radius = 150;
context.font = '30pt Calibri';
context.textAlign = 'center';
context.fillStyle = 'blue';
context.strokeStyle = 'blue';
context.lineWidth = 4;
drawTextAlongArc(context, 'Text along arc path', centerX, centerY, radius, angle);
// draw circle underneath text
context.arc(centerX, centerY, radius - 10, 0, 2 * Math.PI, false);
context.stroke();
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="250"></canvas>
</body>
</html>
You can't in any built in way. Please note that SVG natively does support text along paths, so you might want to consider SVG instead!
But you can write custom code in order to achieve the same effect, as some of us did for this question here: HTML5 Canvas Circle Text

Categories

Resources