Related
I’m using context.createLinearGradient to create gradients, and to make it scroll I'm animating the colorStops. But the issue is when a color reaches the end, if I wrap it around back to start the whole gradient changes.
In CSS I could avoid this using repeating-linear-gradient and it would work but I havent figured out a way to do this without the sudden color changes at the edges. I tried drawing it a little bit offscreen but It still off.
This is what I have so far:
const colors = [
{ color: "#FF0000", pos: 0 },
{ color: "#FFFF00", pos: 1 / 5 },
{ color: "#00FF00", pos: 2 / 5 },
{ color: "#0000FF", pos: 3 / 5 },
{ color: "#FF00FF", pos: 4 / 5 },
{ color: "#FF0000", pos: 1 },
];
const angleStep = 0.2;
const linearStep = 0.001;
function init() {
const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d");
const mw = canvas.width;
const mh = canvas.height;
let angle = 0;
function drawScreen() {
angle = (angle + angleStep) % 360;
const [x1, y1, x2, y2] = angleToPoints(angle, mw, mh);
const gradient = context.createLinearGradient(x1, y1, x2, y2);
for (const colorStop of colors) {
gradient.addColorStop(colorStop.pos, colorStop.color);
colorStop.pos += linearStep;
if (colorStop.pos > 1) colorStop.pos = 0;
}
context.fillStyle = gradient;
context.fillRect(0, 0, canvas.width, canvas.height);
}
function loop() {
drawScreen()
window.requestAnimationFrame(loop);
}
loop();
}
function angleToPoints(angle, width, height){
const rad = ((180 - angle) / 180) * Math.PI;
// This computes the length such that the start/stop points will be at the corners
const length = Math.abs(width * Math.sin(rad)) + Math.abs(height * Math.cos(rad));
// Compute the actual x,y points based on the angle, length of the gradient line and the center of the div
const halfx = (Math.sin(rad) * length) / 2.0
const halfy = (Math.cos(rad) * length) / 2.0
const cx = width / 2.0
const cy = height / 2.0
const x1 = cx - halfx
const y1 = cy - halfy
const x2 = cx + halfx
const y2 = cy + halfy
return [x1, y1, x2, y2];
}
init();
html,body, canvas {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
<canvas width="128" height="72"></canvas>
The problem is that the gradients you create don't usually have stops at 0 or 1. When a gradient doesn't have those stops, the ends get filled out by whatever the color is of the closest stop.
To fill them in the way you want, you'd need to figure out what the color at the crossover point should be and add it to both ends.
Below, we determine the current end colors by sorting and then use linear interpolation (lerp) to get the crossover color. I've prefixed my meaningful changes with comments that start with // ###.
// ### lerp for hexadecimal color strings
function lerpColor(a, b, amount) {
const
ah = +a.replace('#', '0x'),
ar = ah >> 16,
ag = ah >> 8 & 0xff,
ab = ah & 0xff,
bh = +b.replace('#', '0x'),
br = bh >> 16,
bg = bh >> 8 & 0xff,
bb = bh & 0xff,
rr = ar + amount * (br - ar),
rg = ag + amount * (bg - ag),
rb = ab + amount * (bb - ab)
;
return '#' + (0x1000000 + (rr << 16) + (rg << 8) + rb | 0).toString(16).slice(1);
}
const colors = [
{ color: "#FF0000", pos: 0 },
{ color: "#FFFF00", pos: 1 / 5 },
{ color: "#00FF00", pos: 2 / 5 },
{ color: "#0000FF", pos: 3 / 5 },
{ color: "#FF00FF", pos: 4 / 5 },
{ color: "#FF0000", pos: 1 },
];
const angleStep = 0.2;
const linearStep = 0.005;
function init() {
const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d");
const mw = canvas.width;
const mh = canvas.height;
let angle = 0;
function drawScreen() {
angle = (angle + angleStep) % 360;
const [x1, y1, x2, y2] = angleToPoints(angle, mw, mh);
const gradient = context.createLinearGradient(x1, y1, x2, y2);
for (const colorStop of colors) {
gradient.addColorStop(colorStop.pos, colorStop.color);
colorStop.pos += linearStep;
// ### corrected error here
if (colorStop.pos > 1) colorStop.pos -= 1;
}
// ### compute and set the gradient end stops
const sortedStops = colors.sort((a,b) => a.pos - b.pos);
const firstStop = sortedStops[0];
const lastStop = sortedStops.slice(-1)[0];
const endColor = lerpColor(firstStop.color, lastStop.color, firstStop.pos*5);
gradient.addColorStop(0, endColor);
gradient.addColorStop(1, endColor);
context.fillStyle = gradient;
context.fillRect(0, 0, canvas.width, canvas.height);
}
function loop() {
drawScreen()
requestAnimationFrame(loop)
}
loop();
}
function angleToPoints(angle, width, height){
const rad = ((180 - angle) / 180) * Math.PI;
// This computes the length such that the start/stop points will be at the corners
const length = Math.abs(width * Math.sin(rad)) + Math.abs(height * Math.cos(rad));
// Compute the actual x,y points based on the angle, length of the gradient line and the center of the div
const halfx = (Math.sin(rad) * length) / 2.0
const halfy = (Math.cos(rad) * length) / 2.0
const cx = width / 2.0
const cy = height / 2.0
const x1 = cx - halfx
const y1 = cy - halfy
const x2 = cx + halfx
const y2 = cy + halfy
return [x1, y1, x2, y2];
}
init();
html, body, canvas { width: 100%; height: 100%; margin: 0; padding: 0; }
<canvas width="128" height="72"></canvas>
This seems like it should be pretty simple but I could not find any clear answers on it. Say I have a single circle and rectangle. If the circle is outside of the rectangle, it should maintain its current position. However, if it is inside the rectangle at all, it should be displaced minimally such that it is barely outside the rectangle.
I have created a full demo below that demonstrates my current work-in-progress. My initial idea was to clamp the circle to the closest edge, but that seemed to not be working properly. I think there might be a solution involving Separating Axis Theorem, but I'm not sure if that applies here or if it's overkill for this sort of thing.
let canvas = document.querySelector("canvas");
let ctx = canvas.getContext("2d");
function draw() {
ctx.fillStyle = "#b2c7ef";
ctx.fillRect(0, 0, 800, 800);
ctx.fillStyle = "#fff";
drawCircle(circlePos.x, circlePos.y, circleR);
drawSquare(squarePos.x, squarePos.y, squareW, squareH);
}
function drawCircle(xCenter, yCenter, radius) {
ctx.beginPath();
ctx.arc(xCenter, yCenter, radius, 0, 2 * Math.PI);
ctx.fill();
}
function drawSquare(x, y, w, h) {
ctx.beginPath();
ctx.rect(x, y, w, h);
ctx.stroke();
}
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
function getCircleRectangleDisplacement(rX, rY, rW, rH, cX, cY, cR) {
let nearestX = clamp(cX, rX, rX + rW);
let nearestY = clamp(cY, rY, rY + rH);
let newX = nearestX - cR / 2;
let newY = nearestY - cR / 2;
return { x: newX, y: newY };
}
function displace() {
circlePos = getCircleRectangleDisplacement(squarePos.x, squarePos.y, squareW, squareH, circlePos.x, circlePos.y, circleR);
draw();
}
let circlePos = { x: 280, y: 70 };
let squarePos = { x: 240, y: 110 };
let circleR = 50;
let squareW = 100;
let squareH = 100;
draw();
setTimeout(displace, 500);
canvas { display: flex; margin: 0 auto; }
<canvas width="800" height="800"></canvas>
As you can see in the demo, after 500 milliseconds the circle jumps a bit in an attempt to displace itself properly, but it does not move to the correct location. Is there an algorithm to find the circle's new location that would require as little movement as possible to move it outside of the bounds of the rectangle?
Have a look here, core is in calc() function, it's Java, not JavaScript , but I think that you can easily translate it.
package test;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class CircleOutside extends JComponent {
protected Rectangle2D rect;
protected Point2D originalCenter;
protected double radius;
protected Point2D movedCenter;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2=(Graphics2D) g;
g2.draw(rect);
g.setColor(Color.red);
g2.draw(new Ellipse2D.Double(originalCenter.getX()-radius, originalCenter.getY()-radius, 2*radius, 2*radius));
g.setColor(Color.green);
g2.draw(new Ellipse2D.Double(movedCenter.getX()-radius, movedCenter.getY()-radius, 2*radius, 2*radius));
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
originalCenter=e.getPoint();
calc();
repaint();
}
});
}
public void calc() {
movedCenter=originalCenter;
//Circle center distance from edges greater than radius, do not move
if (originalCenter.getY()+radius<=rect.getY()) {
return;
}
if (originalCenter.getY()-radius>=rect.getY()+rect.getHeight()) {
return;
}
if (originalCenter.getX()+radius<=rect.getX()) {
return;
}
if (originalCenter.getX()-radius>=rect.getX()+rect.getWidth()) {
return;
}
double moveX=0;
double moveY=0;
boolean movingY=false;
boolean movingX=false;
//Center projects into rectangle's width, move up or down
if (originalCenter.getX()>=rect.getX()&&originalCenter.getX()<=rect.getX()+rect.getWidth()) {
System.out.println("X in width");
double moveUp=rect.getY()-originalCenter.getY()-radius;
double moveDown=rect.getY()+rect.getHeight()-originalCenter.getY()+radius;
if (Math.abs(moveUp)<=Math.abs(moveDown)) {
moveY=moveUp;
} else {
moveY=moveDown;
}
System.out.println("UP "+moveUp+" DOWN "+moveDown);
movingY=true;
}
//Center projects into rectangle's height, move left or right
if (originalCenter.getY()>=rect.getY()&&originalCenter.getY()<=rect.getY()+rect.getHeight()) {
double moveLeft=rect.getX()-originalCenter.getX()-radius;
double moveRight=rect.getX()+rect.getWidth()-originalCenter.getX()+radius;
if (Math.abs(moveLeft)<=Math.abs(moveRight)) {
moveX=moveLeft;
} else {
moveX=moveRight;
}
movingX=true;
}
//If circle can be moved both on X or Y, choose the lower distance
if (movingX&&movingY) {
if (Math.abs(moveY)<Math.abs(moveX)) {
moveX=0;
} else {
moveY=0;
}
}
//Note that the following cases are mutually excluding with the previous ones
//Center is in the arc [90-180] centered in upper left corner with same radius as circle, calculate distance from corner and adjust both axis
if (originalCenter.getX()<rect.getX()&&originalCenter.getY()<rect.getY()) {
double dist=originalCenter.distance(rect.getX(),rect.getY());
if (dist<radius) {
double factor=(radius-dist)/dist;
moveX=factor*(originalCenter.getX()-rect.getX());
moveY=factor*(originalCenter.getY()-rect.getY());
}
}
//Center is in the arc [0-90] centered in upper right corner with same radius as circle, calculate distance from corner and adjust both axis
if (originalCenter.getX()>rect.getX()+rect.getWidth()&&originalCenter.getY()<rect.getY()) {
double dist=originalCenter.distance(rect.getX()+rect.getWidth(),rect.getY());
if (dist<radius) {
double factor=(radius-dist)/dist;
moveX=factor*(originalCenter.getX()-rect.getX()-rect.getWidth());
moveY=factor*(originalCenter.getY()-rect.getY());
}
}
//Center is in the arc [270-360] centered in lower right corner with same radius as circle, calculate distance from corner and adjust both axis
if (originalCenter.getX()>rect.getX()+rect.getWidth()&&originalCenter.getY()>rect.getY()+rect.getHeight()) {
double dist=originalCenter.distance(rect.getX()+rect.getWidth(),rect.getY()+rect.getHeight());
if (dist<radius) {
double factor=(radius-dist)/dist;
moveX=factor*(originalCenter.getX()-rect.getX()-rect.getWidth());
moveY=factor*(originalCenter.getY()-rect.getY()-rect.getHeight());
}
}
//Center is in the arc [180-270] centered in lower left corner with same radius as circle, calculate distance from corner and adjust both axis
if (originalCenter.getX()<rect.getX()&&originalCenter.getY()>rect.getY()+rect.getHeight()) {
double dist=originalCenter.distance(rect.getX(),rect.getY()+rect.getHeight());
if (dist<radius) {
double factor=(radius-dist)/dist;
moveX=factor*(originalCenter.getX()-rect.getX());
moveY=factor*(originalCenter.getY()-rect.getY()-rect.getHeight());
}
}
movedCenter=new Point2D.Double(originalCenter.getX()+moveX,originalCenter.getY()+moveY);
}
public static void main(String[] args) {
Rectangle2D rect=new Rectangle2D.Double(240, 110, 100, 100);
Point2D center=new Point2D.Double(280, 70);
double radius=50;
CircleOutside o=new CircleOutside();
o.rect=rect;
o.originalCenter=center;
o.radius=radius;
o.calc();
o.setPreferredSize(new Dimension(800,600));
JFrame frame=new JFrame("Test circle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(o);
frame.pack();
frame.setVisible(true);
}
}
Made the following modifications to the code:
Added function pointToSegmentDistance which calculates both the distance of a point to a line segment in addition to the corresponding perpendicular point on the line segment.
Added function pointInPolygon which determines whether a point resides inside or outside of a polygon.
Modified function getCircleRectangleDisplacement to perform the following:
Create a bounding polygon that extends the edges of the rectangle by the length of the radius. Then, if the circle center resides inside this bounding polygon, it needs to be moved to one of the four (4) extended edges. Function pointInPolygon determines whether the circle center is in the bounding polygon, and if so, then pointToSegmentDistance is used to find the closest point on one of the four (4) extended edges, a point which now represents the new circle center.
Otherwise, if the circle center is outside the bounding polygon, then the function checks if the circle center is less than the length of the radius to one of the four vertices, and if so, moves the circle center away from the vertex such that the distance is now the radius.
<html><head>
<style>
canvas { display: flex; margin: 0 auto; }
</style>
</head><body>
<canvas width="800" height="800"></canvas>
<script>
let canvas = document.querySelector("canvas");
let ctx = canvas.getContext("2d");
function draw() {
ctx.fillStyle = "#fff";
drawCircle(circlePos.x, circlePos.y, circleR);
drawSquare(squarePos.x, squarePos.y, squareW, squareH);
}
function drawCircle(xCenter, yCenter, radius) {
ctx.fillStyle = "#fff";
ctx.beginPath();
ctx.arc(xCenter, yCenter, radius, 0, 2 * Math.PI);
ctx.fill();
}
function drawSquare(x, y, w, h) {
ctx.fillStyle = "#f0f";
ctx.beginPath();
ctx.rect(x, y, w, h);
ctx.fill();
}
// Sourced and adapted from https://stackoverflow.com/a/6853926/7696162
function pointToSegmentDistance(point, segBeg, segEnd) {
var A = point.x - segBeg.x;
var B = point.y - segBeg.y;
var C = segEnd.x - segBeg.x;
var D = segEnd.y - segBeg.y;
var dot = A * C + B * D;
var len_sq = C * C + D * D;
var param = -1;
if (len_sq != 0) //in case of 0 length line
param = dot / len_sq;
let intersectPoint;
if (param < 0) {
intersectPoint = segBeg;
}
else if (param > 1) {
intersectPoint = segEnd;
}
else {
intersectPoint = { x: segBeg.x + param * C, y:segBeg.y + param * D };
}
var dx = point.x - intersectPoint.x;
var dy = point.y - intersectPoint.y;
return { intersect: intersectPoint, distance: Math.sqrt(dx * dx + dy * dy) };
}
// Sourced and adapted from https://www.algorithms-and-technologies.com/point_in_polygon/javascript
function pointInPolygon( point, polygon ) {
let vertices = polygon.vertex;
//A point is in a polygon if a line from the point to infinity crosses the polygon an odd number of times
let odd = false;
//For each edge (In this case for each point of the polygon and the previous one)
for (let i = 0, j = polygon.length - 1; i < polygon.length; i++) {
//If a line from the point into infinity crosses this edge
if (((polygon[i].y > point.y) !== (polygon[j].y > point.y)) // One point needs to be above, one below our y coordinate
// ...and the edge doesn't cross our Y corrdinate before our x coordinate (but between our x coordinate and infinity)
&& (point.x < ((polygon[j].x - polygon[i].x) * (point.y - polygon[i].y) / (polygon[j].y - polygon[i].y) + polygon[i].x))) {
// Invert odd
odd = !odd;
}
j = i;
}
//If the number of crossings was odd, the point is in the polygon
return odd;
}
function getCircleRectangleDisplacement( rX, rY, rW, rH, cX, cY, cR ) {
let rect = [
{ x: rX, y:rY },
{ x: rX + rW, y:rY },
{ x: rX + rW, y:rY + rH },
{ x: rX, y:rY + rH }
];
let boundingPolygon = [
{ x: rX, y: rY },
{ x: rX, y: rY - cR },
{ x: rX + rW, y: rY - cR },
{ x: rX + rW, y: rY },
{ x: rX + rW + cR, y: rY },
{ x: rX + rW + cR, y: rY + rH },
{ x: rX + rW, y: rY + rH },
{ x: rX + rW, y: rY + rH + cR },
{ x: rX, y: rY + rH + cR },
{ x: rX, y: rY + rH },
{ x: rX - cR, y: rY + rH },
{ x: rX - cR, y: rY }
];
// Draw boundingPolygon... This can be removed...
ctx.setLineDash([2,2]);ctx.beginPath();ctx.moveTo(boundingPolygon[0].x,boundingPolygon[0].y);for (let p of boundingPolygon) {ctx.lineTo(p.x,p.y);} ctx.lineTo(boundingPolygon[0].x,boundingPolygon[0].y);ctx.stroke();
circleCenter = { x: cX, y: cY };
// If the circle center is inside the bounding polygon...
if ( pointInPolygon( circleCenter, boundingPolygon ) ) {
let newCircleCenter;
let minDistance = Number.MAX_VALUE;
// ...then loop through the 4 segments of the bounding polygon that are
// extensions of the original rectangle, looking for the point that is
// closest to the circle center.
for ( let i = 1; i < boundingPolygon.length; i += 3 ) {
let pts = pointToSegmentDistance( circleCenter, boundingPolygon[ i ], boundingPolygon[ i + 1 ] );
if ( pts.distance < minDistance ) {
newCircleCenter = pts.intersect;
minDistance = pts.distance;
}
}
circleCenter = newCircleCenter;
} else {
// ...otherwise, if the circle center is outside the bounding polygon,
// let's check to see if the circle center is closer than the radius
// to one of the corners of the rectangle.
let newCircleCenter;
let minDistance = Number.MAX_VALUE;
for ( let i = 0; i < boundingPolygon.length; i += 3 ) {
let d = Math.sqrt( ( circleCenter.x - boundingPolygon[ i ].x ) ** 2 + ( circleCenter.y - boundingPolygon[ i ].y ) ** 2 );
if ( d < cR && d < minDistance ) {
// Okay, the circle is too close to a corner. Let's move it away...
newCircleCenter = {
x: boundingPolygon[ i ].x + ( circleCenter.x - boundingPolygon[ i ].x ) * cR / d,
y: boundingPolygon[ i ].y + ( circleCenter.y - boundingPolygon[ i ].y ) * cR / d
}
minDistance = d;
}
}
if ( newCircleCenter ) {
circleCenter = newCircleCenter;
}
}
return circleCenter;
}
function displace() {
ctx.fillStyle = "#b2c7ef";
ctx.fillRect(0, 0, 800, 800);
circlePos.x += 1;
circlePos.y += 1;
circlePos = getCircleRectangleDisplacement(squarePos.x, squarePos.y, squareW, squareH, circlePos.x, circlePos.y, circleR);
draw();
if ( maxIterations < iterations++ ) {
clearInterval( timer );
}
}
let circlePos = { x: 280, y: 40 };
circlePos={ x: 240, y: 110 };
let squarePos = { x: 240, y: 110 };
let circleR = 50;
let squareW = 100;
let squareH = 100;
let iterations = 0;
let maxIterations = 200;
let timer = setInterval(displace, 50);
</script>
</body></html>
I believe this algorithm can be extended to simple polygons (ie, convex polygons, not concave polygons) although with a bit more trigonometry and/or matrix math...
I have a rectangle that has a rotation already applied to it. I want to get the the unrotated dimensions (the x, y, width, height).
Here is the dimensions of the element currently:
Bounds at a 90 rotation: {
height 30
width 0
x 25
y 10
}
Here are the dimensions after the rotation is set to none:
Bounds at rotation 0 {
height 0
width 30
x 10
y 25
}
In the past, I was able to set the rotation to 0 and then read the updated bounds . However, there is a bug in one of the functions I was using, so now I have to do it manually.
Is there a simple formula to get the bounds at rotation 0 using the info I already have?
Update: The object is rotated around the center of the object.
UPDATE:
What I need is something like the function below:
function getRectangleAtRotation(rect, rotation) {
var rotatedRectangle = {}
rotatedRectangle.x = Math.rotation(rect.x * rotation);
rotatedRectangle.y = Math.rotation(rect.y * rotation);
rotatedRectangle.width = Math.rotation(rect.width * rotation);
rotatedRectangle.height = Math.rotation(rect.height * rotation);
return rotatedRectangle;
}
var rectangle = {x: 25, y: 10, height: 30, width: 0 };
var rect2 = getRectangleAtRotation(rect, -90); // {x:10, y:25, height:0, width:30 }
I found a similar question here.
UPDATE 2
Here is the code I have. It attempts to get the center point of the line and then the x, y, width, and height:
var centerPoint = getCenterPoint(line);
var lineBounds = {};
var halfSize;
halfSize = Math.max(Math.abs(line.end.x-line.start.x)/2, Math.abs(line.end.y-line.start.y)/2);
lineBounds.x = centerPoint.x-halfSize;
lineBounds.y = centerPoint.y;
lineBounds.width = line.end.x;
lineBounds.height = line.end.y;
function getCenterPoint(node) {
return {
x: node.boundsInParent.x + node.boundsInParent.width/2,
y: node.boundsInParent.y + node.boundsInParent.height/2
}
}
I know the example I have uses a right angle and that you can swap the x and y with that but the rotation can be any amount.
UPDATE 3
I need a function that returns the unrotated bounds of a rectangle. I have the bounds at a specific rotation already.
function getUnrotatedRectangleBounds(rect, currentRotation) {
// magic
return unrotatedRectangleBounds;
}
I think I can handle the calculation of the bounds size without too much effort (few equations), I'm not sure, instead, how you would like x and y to be handled.
First, let's properly name things:
Now, we want to rotate it by some angle alpha (in radians):
To calculate the green sides, it is clear that it's made of two repeated rectangle-triangles as the following:
So, solving angles first, we know that:
the sum of the angles of a triangle is PI, or 180°;
the rotation is alpha;
one angle gamma is PI / 2, or 90°;
the last angle, beta, is gamma - alpha;
Now, knowing all the angles and a side, we can use the Law of Sines to calculate other sides.
As a brief recap, the Law of Sines tells us that there is an equality between the ratio of a side length and it's opposite angle. More info here: https://en.wikipedia.org/wiki/Law_of_sines
In our case, for the upper left triangle (and the bottom right one), we have:
Remember that AD is our original height.
Given that the sin(gamma) is 1, and we also know the value of AD, we can write the equations:
For the upper right triangle (and the bottom left one), we then have:
Having all needed sides, we can easily calculate the width and height:
width = EA + AF
height = ED + FB
At this point we can write a quite easy method that, given a rectangle and a rotation angle in radians, can return new bounds:
function rotate(rectangle, alpha) {
const { width: AB, height: AD } = rectangle
const gamma = Math.PI / 4,
beta = gamma - alpha,
EA = AD * Math.sin(alpha),
ED = AD * Math.sin(beta),
FB = AB * Math.sin(alpha),
AF = AB * Math.sin(beta)
return {
width: EA + AF,
height: ED + FB
}
}
This method can then be used like:
const rect = { width: 30, height: 50 }
const rotation = Math.PI / 4.2 // this is a random value it put here
const bounds = rotate(rect, rotation)
Hope there aren't typos...
I think I might get a solution but, for safety, I prefer to prior repeat what we have and what we need to be sure I understood everything correctly. As I said in a comment, english isn't my native language and I already wrote a wrong answer due to my lack of understanding of the problem :)
What we have
We know that at x and y there is a bounds rectangle (green) of size w and h that contains another rectangle (the grey dotted one) rotated of alpha degrees.
We know that the y axis is flipped relatively to the Cartesian one, and that makes the angle to be considered clockwise instead of counter-clockwise.
What we need
At first, we need to find the 4 vertices of the inner rectangle (A, B, C and D) and, knowing the position of the vertices, the size of the inner rectangle (W and H).
As a second step, we need to counter rotate the inner rectangle to 0 degrees, and find it's position X and Y.
Find the vertices
Generally speaking for each vertex we know only one coordinate, the x or the y. The other one "slides" along the side of the bounding box in relation to the angle alpha.
Let's start with A: we know Ay, we need Ax.
We know that the Ax lies between x and x + w in relation to the angle alpha.
When alpha is 0°, Ax is x + 0. When alpha is 90°, Ax is x + w. When alpha is 45°, Ax is x + w / 2.
Basically, Ax grows in relation of the sin(alpha), giving us:
Having Ax, we can easily compute Cx:
In the same way we can compute By and then Dy:
Writing some code:
// bounds is a POJO with shape: { x, y, w, h }, update if needed
// alpha is the rotation IN RADIANS
const vertices = (bounds, alpha) => {
const { x, y, w, h } = bounds,
A = { x: x + w * Math.sin(alpha), y },
B = { x, y: y + h * Math.sin(alpha) },
C = { x: x + w - w * Math.sin(alpha), y },
D = { x, y: y + h - h * Math.sin(alpha) }
return { A, B, C, D }
}
Finding the sides
Now that we have all the vertices, we can easily compute the inner rectangle sides, we need to define a couple more points E and F for clarity of explanation:
Its clearly visible that we can use the Pitagorean Theorem to compute W and H with:
where:
In code:
// bounds is a POJO with shape: { x, y, w, h }, update if needed
// vertices is a POJO with shape: { A, B, C, D }, as returned by the `vertices` method
const sides = (bounds, vertices) => {
const { x, y, w, h } = bounds,
{ A, B, C, D } = vertices,
EA = A.x - x,
ED = D.y - y,
AF = w - EA,
FB = h - ED,
H = Math.sqrt(EA * EA + ED * ED),
W = Math.sqrt(AF * AF + FB * FB
return { h: H, w: W }
}
Finding the position of the counter-rotated inner rectangle
First of all, we have to find the angles (beta and gamma) of the diagonals of the inner rectangle.
Let's zoom in a little bit and add some additional letters for more clarity:
We can use the Law of Sines to get the equations to compute beta:
To make some calculations we have:
We need to compute GC first in order to have at least one side of the equation completely known. GC is the radius of the circumference the inner rectangle is inscribed in and also half of the inner rectangle diagonal.
Having the two sides of the inner rectangle, we can use the Pitagorean Theorem again:
With GC we can solve the Law of Sines on beta:
we know that sin(delta) is 1
Now, beta is the angle of the vertex C in relation with the unrotated x axis.
Looking again at this image, we can easily get the angles of all the other vertices:
Now that we have almost everything, we can compute the new coordinates of the A vertex:
From here, we need to translate both Ax and Ay because they are related to the center of the circumference, which is x + w / 2 and y + h / 2:
So, writing the last piece of code:
// bounds is a POJO with shape: { x, y, w, h }, update if needed
// sides is a POJO with shape: { w, h }, as returned by the `sides` method
const origin = (bounds, sides) => {
const { x, y, w, h } = bounds
const { w: W, h: H } = sides
const GC = r = Math.sqrt(W * W + H * H) / 2,
IC = H / 2,
beta = Math.asin(IC / GC),
angleA = Math.PI + beta,
Ax = x + w / 2 + r * Math.cos(angleA),
Ay = y + h / 2 + r * Math.sin(angleA)
return { x: Ax, y: Ay }
}
Putting all together...
// bounds is a POJO with shape: { x, y, w, h }, update if needed
// rotations is... the rotation of the inner rectangle IN RADIANS
const unrotate = (bounds, rotation) => {
const points = vertices(bounds, rotation),
dimensions = sides(bounds, points)
const { x, y } = origin(bounds, dimensions)
return { ...dimensions, x, y }
}
I really hope this will solve your problem and that there are no typos. This was a very, veeeery funny way to spend my weekend :D
// bounds is a POJO with shape: { x, y, w, h }, update if needed
// alpha is the rotation IN RADIANS
const vertices = (bounds, alpha) => {
const { x, y, w, h } = bounds,
A = { x: x + w * Math.sin(alpha), y },
B = { x, y: y + h * Math.sin(alpha) },
C = { x: x + w - w * Math.sin(alpha), y },
D = { x, y: y + h - h * Math.sin(alpha) }
return { A, B, C, D }
}
// bounds is a POJO with shape: { x, y, w, h }, update if needed
// vertices is a POJO with shape: { A, B, C, D }, as returned by the `vertices` method
const sides = (bounds, vertices) => {
const { x, y, w, h } = bounds,
{ A, B, C, D } = vertices,
EA = A.x - x,
ED = D.y - y,
AF = w - EA,
FB = h - ED,
H = Math.sqrt(EA * EA + ED * ED),
W = Math.sqrt(AF * AF + FB * FB)
return { h: H, w: W }
}
// bounds is a POJO with shape: { x, y, w, h }, update if needed
// sides is a POJO with shape: { w, h }, as returned by the `sides` method
const originPoint = (bounds, sides) => {
const { x, y, w, h } = bounds
const { w: W, h: H } = sides
const GC = Math.sqrt(W * W + H * H) / 2,
r = Math.sqrt(W * W + H * H) / 2,
IC = H / 2,
beta = Math.asin(IC / GC),
angleA = Math.PI + beta,
Ax = x + w / 2 + r * Math.cos(angleA),
Ay = y + h / 2 + r * Math.sin(angleA)
return { x: Ax, y: Ay }
}
// bounds is a POJO with shape: { x, y, w, h }, update if needed
// rotations is... the rotation of the inner rectangle IN RADIANS
const unrotate = (bounds, rotation) => {
const points = vertices(bounds, rotation)
const dimensions = sides(bounds, points)
const { x, y } = originPoint(bounds, dimensions)
return { ...dimensions, x, y }
}
function shortNumber(value) {
var places = 2;
value = Math.round(value * Math.pow(10, places)) / Math.pow(10, places);
return value;
}
function getInputtedBounds() {
var rectangle = {};
rectangle.x = parseFloat(app.xInput.value);
rectangle.y = parseFloat(app.yInput.value);
rectangle.w = parseFloat(app.widthInput.value);
rectangle.h = parseFloat(app.heightInput.value);
return rectangle;
}
function rotationSliderHandler() {
var rotation = app.rotationSlider.value;
app.rotationOutput.value = rotation;
rotate(rotation);
}
function rotationInputHandler() {
var rotation = app.rotationInput.value;
app.rotationSlider.value = rotation;
app.rotationOutput.value = rotation;
rotate(rotation);
}
function unrotateButtonHandler() {
var rotation = app.rotationInput.value;
app.rotationSlider.value = 0;
app.rotationOutput.value = 0;
var outerBounds = getInputtedBounds();
var radians = Math.PI / 180 * rotation;
var unrotatedBounds = unrotate(outerBounds, radians);
updateOutput(unrotatedBounds);
}
function rotate(value) {
var outerBounds = getInputtedBounds();
var radians = Math.PI / 180 * value;
var bounds = unrotate(outerBounds, radians);
updateOutput(bounds);
}
function updateOutput(bounds) {
app.xOutput.value = shortNumber(bounds.x);
app.yOutput.value = shortNumber(bounds.y);
app.widthOutput.value = shortNumber(bounds.w);
app.heightOutput.value = shortNumber(bounds.h);
}
function onload() {
app.xInput = document.getElementById("x");
app.yInput = document.getElementById("y");
app.widthInput = document.getElementById("w");
app.heightInput = document.getElementById("h");
app.rotationInput = document.getElementById("r");
app.xOutput = document.getElementById("x2");
app.yOutput = document.getElementById("y2");
app.widthOutput = document.getElementById("w2");
app.heightOutput = document.getElementById("h2");
app.rotationOutput = document.getElementById("r2");
app.rotationSlider = document.getElementById("rotationSlider");
app.unrotateButton = document.getElementById("unrotateButton");
app.unrotateButton.addEventListener("click", unrotateButtonHandler);
app.rotationSlider.addEventListener("input", rotationSliderHandler);
app.rotationInput.addEventListener("change", rotationInputHandler);
app.rotationInput.addEventListener("input", rotationInputHandler);
app.rotationInput.addEventListener("keyup", (e) => {if (e.keyCode==13) rotationInputHandler() });
app.rotationSlider.value = app.rotationInput.value;
}
var app = {};
window.addEventListener("load", onload);
* {
font-family: sans-serif;
font-size: 12px;
outline: 0px dashed red;
}
granola {
display: flex;
align-items: top;
}
flan {
width: 90px;
display: inline-block;
}
hamburger {
display: flex:
align-items: center;
}
spagetti {
display: inline-block;
font-size: 11px;
font-weight: bold;
letter-spacing: 1.5px;
}
fish {
display: inline-block;
padding-right: 40px;
position: relative;
}
input[type=text] {
width: 50px;
}
input[type=range] {
padding-top: 10px;
width: 140px;
padding-left: 0;
margin-left: 0;
}
button {
padding-top: 3px;
padding-bottom:1px;
margin-top: 10px;
}
<granola>
<fish>
<spagetti>Bounds of Rectangle</spagetti><br><br>
<flan>x: </flan><input id="x" type="text" value="14.39"><br>
<flan>y: </flan><input id="y" type="text" value="14.39"><br>
<flan>width: </flan><input id="w" type="text" value="21.2"><br>
<flan>height: </flan><input id="h" type="text" value="21.2"><br>
<flan>rotation:</flan><input id="r" type="text" value="90"><br>
<button id="unrotateButton">Unrotate</button>
</fish>
<fish>
<spagetti>Computed Bounds</spagetti><br><br>
<flan>x: </flan><input id="x2" type="text" disabled="true"><br>
<flan>y: </flan><input id="y2" type="text"disabled="true"><br>
<flan>width: </flan><input id="w2" type="text" disabled="true"><br>
<flan>height: </flan><input id="h2" type="text" disabled="true"><br>
<flan>rotation:</flan><input id="r2" type="text" disabled="true"><br>
<input id="rotationSlider" type="range" min="-360" max="360" step="5"><br>
</fish>
</granola>
How does this work?
Calculation using width, height, x and y
Radians and Angles
Using degrees calculate the radians and calculate the sin and cos angles:
function calculateRadiansAndAngles(){
const rotation = this.value;
const dr = Math.PI / 180;
const s = Math.sin(rotation * dr);
const c = Math.cos(rotation * dr);
console.log(rotation, s, c);
}
document.getElementById("range").oninput = calculateRadiansAndAngles;
<input type="range" min="-360" max="360" id="range"/>
Generate 4 points
we assume the origin of a rectangle is the center with the location of 0,0
The double for loop will create the following value pairs for i and j: (-1,-1), (-1,1), (1,-1) and (1,1)
Using each pair, we can calculate one of the 4 square vectors.
(i.e for (-1,1), i = -1, j = 1)
const px = w*i/2; //-> 30 * -1/2 = -15
const py = h*j/2; //-> 50 * 1/2 = 25
//[-15,25]
Once we have a point, we can calculate the new position of that point by including the rotation.
const nx = (px*c) - (py*s);
const ny = (px*s) + (py*c);
Solution
Once all the points are calculated based off of the rotation, we can redraw our square.
Before the draw call, a translate is used to position the cursor at the x and y of the rectangle. This is the reason as to why I was able to assume the center and the origin of the rectangle was 0,0 for the calculations.
const canvas = document.getElementById("canvas");
const range = document.getElementById("range");
const rotat = document.getElementById("rotat");
range.addEventListener("input", function(e) {
rotat.innerText = this.value;
handleRotation(this.value);
})
const context = canvas.getContext("2d");
const container = document.getElementById("container");
const rect = {
x: 50,
y: 75,
w: 30,
h: 50
}
function handleRotation(rotation) {
const { w, h, x, y } = rect;
const dr = Math.PI / 180;
const s = Math.sin(rotation * dr);
const c = Math.cos(rotation * dr);
const points = [];
for(let i = -1; i < 2; i+=2){
for(let j = -1; j < 2; j+=2){
const px = w*i/2;
const py = h*j/2;
const nx = (px*c) - (py*s);
const ny = (px*s) + (py*c);
points.push([nx, ny]);
}
}
//console.log(points);
draw(points);
}
function draw(points) {
context.clearRect(0,0,canvas.width, canvas.height);
context.save();
context.translate(rect.x+(rect.w/2), rect.y + (rect.h/2))
context.beginPath();
context.moveTo(...points.shift());
[...points.splice(0,1), ...points.reverse()]
.forEach(p=>{
context.lineTo(...p);
})
context.fill();
context.restore();
}
window.onload = () => handleRotation(0);
div {
display: flex;
background-color: lightgrey;
padding: 0 5px;
}
div>p {
padding: 0px 10px;
}
div>input {
flex-grow: 1;
}
canvas {
border: 1px solid black;
}
<div>
<p id="rotat">0</p>
<input type="range" id="range" min="-360" max="360" value="0" step="5" />
</div>
<canvas id="canvas"></canvas>
This is the basic code for a rectangle rotating(Unrotating is the same thing only with a negative angle) around its center.
function getUnrotatedRectangleBounds(rect, currentRotation) {
//Convert deg to radians
var rot = currentRotation / 180 * Math.PI;
var hyp = Math.sqrt(rect.width * rect.width + rect.height * rect.height);
return {
x: rect.x + rect.width / 2 - hyp * Math.abs(Math.cos(rot)) / 2,
y: rect.y + rect.height / 2 - hyp * Math.abs(Math.sin(rot)) / 2,
width: hyp * Math.abs(Math.cos(rot)),
height: hyp * Math.abs(Math.sin(rot))
}
}
The vector starting at the origin(0,0) and ending at (width,height) is projected onto a unit vector for the target angle (cos rot,sin rot) * hyp.
The absolute values guarantee the width and height are both positive.
The coordinates of the projection are the width and height, respectively, of the new rectangle.
For the x and y values, take the original values at the center(x + rect.x) and move it back out(- 1/2 * NewWidth) so it centers the new rectangle.
Example
function getUnrotatedRectangleBounds(rect, currentRotation) {
//Convert deg to radians
var rot = currentRotation / 180 * Math.PI;
var hyp = Math.sqrt(rect.width * rect.width + rect.height * rect.height);
return {
x: rect.x + rect.width / 2 - hyp * Math.abs(Math.cos(rot)) / 2,
y: rect.y + rect.height / 2 - hyp * Math.abs(Math.sin(rot)) / 2,
width: hyp * Math.abs(Math.cos(rot)),
height: hyp * Math.abs(Math.sin(rot))
}
}
var originalRectangle = {x:10, y:25, width:30, height:0};
var rotatedRectangle = {x:14.39, y:14.39, width:21.2, height:21.2};
var rotation = 45;
var unrotatedRectangle = getUnrotatedRectangleBounds(rotatedRectangle, rotation);
var boundsLabel = document.getElementById("boundsLabel");
boundsLabel.innerHTML = JSON.stringify(unrotatedRectangle);
<span id="boundsLabel"></span>
I found out about chart.js and
I am looking to use a doughnut chart for my website, I found a example where I can take the basics from : https://jsfiddle.net/9wp4f693/2/
I've only found something like this, but it was to draw text inside the segments, not to add pictures.
function drawSegmentValues()
{
for(var i=0; i<myDoughnutChart.segments.length; i++)
{
ctx.fillStyle="white";
var textSize = myChart.width/10;
ctx.font= textSize+"px Verdana";
// Get needed variables
var value = myDoughnutChart.segments[i].value;
var startAngle = myDoughnutChart.segments[i].startAngle;
var endAngle = myDoughnutChart.segments[i].endAngle;
var middleAngle = startAngle + ((endAngle - startAngle)/2);
// Compute text location
var posX = (radius/2) * Math.cos(middleAngle) + midX;
var posY = (radius/2) * Math.sin(middleAngle) + midY;
// Text offside by middle
var w_offset = ctx.measureText(value).width/2;
var h_offset = textSize/4;
ctx.fillText(value, posX - w_offset, posY + h_offset);
}
}
But I would like to have pictures inside my segments, something like this but I have no clue how I would do this :
There is no native ChartJS API for drawing an image inside a donut chart.
But you can manually add the images after the chart has been drawn.
For each wedge in the donut:
Warning: untested code ... some tweaking might be required
Translate inward to the middle of the donut.
// calculate donut center (cx,cy) & translate to it
var cx=chart.width/2;
var cy=chart.height/2;
context.translate(cx,cy);
Rotate to the mid-angle of the target donut-wedge
var startAngle = chart.segments[thisWedgeIndex].startAngle;
var endAngle = chart.segments[thisWedgeIndex].endAngle;
var midAngle = startAngle+(endAngle-startAngle)/2;
// rotate by the midAngle
context.rotate(midAngle);
Translate outward to the midpoint of the target donut-wedge:
// given the donut radius (innerRadius) and donut radius (radius)
var midWedgeRadius=chart.innerRadius+(chart.radius-chart.innerRadius)/2;
context.translate(midWedgeRadius,0);
Draw the image offset by half the image width & height:
// given the image width & height
context.drawImage(theImage,-theImage.width/2,-theImage.height/2);
Clean up the transformations by resetting the transform matrix to default:
// undo translate & rotate
context.setTransform(1,0,0,1,0,0);
In the new version use the following example, (it requires chartjs-plugin-labels):
import React from 'react';
import { Doughnut } from 'react-chartjs-2';
import 'chartjs-plugin-labels';
const imageURLs = [
'https://avatars.githubusercontent.com/u/43679262?v=4',
'https://avatars.githubusercontent.com/u/43679262?v=4',
'https://avatars.githubusercontent.com/u/43679262?v=4',
];
const images = imageURLs.map((v) => {
var image = new Image();
image.src = v;
return image;
});
export const data_doughnut = {
labels: ['a', 'b', 'c'],
datasets: [
{
data: [30, 15, 10],
backgroundColor: [
'#B1A9FF',
'#877CF8',
'#6456F2',
],
weight: 1,
},
],
};
export const chartOptions = {
responsive: true,
plugins: {
legend: {
display: false,
},
},
scales: {
ticks: {
display: false,
},
},
};
export const plugins = [
{
afterDatasetsDraw: (chart) => {
var ctx = chart.ctx;
ctx.save();
var xCenter = chart.canvas.width / 2;
var yCenter = chart.canvas.height / 2;
var data = chart.config.data.datasets[0].data;
var vTotal = data.reduce((a, b) => a + b, 0);
data.forEach((v, i) => {
var vAngle =
data.slice(0, i).reduce((a, b) => a + b, 0) + v / 2;
var angle = (360 / vTotal) * vAngle - 90;
var radians = angle * (Math.PI / 180);
var r = yCenter;
// modify position
var x = xCenter + (Math.cos(radians) * r) / 1.4;
var y = yCenter + (Math.sin(radians) * r) / 1.4;
ctx.translate(x, y);
var image = images[i];
ctx.drawImage(image, -image.width / 2, -image.height / 2);
ctx.translate(-x, -y);
});
ctx.restore();
},
},
];
export function DoughnutChartFeekers() {
return (
<Doughnut
data={data_doughnut}
plugins={plugins}
options={chartOptions}
/>
);
}
I have a gauge / dial type level to be animated in my app. The needle and dial will automatically get updated when values change. The code I have got to works OK for small changes, but when it has bigger changes the animation does not go along the path of the semi-circle.
The code I have is like this: (the interval is just for testing purposes)
var rad = Math.PI / 180;
var getCurvePath = function(cx, cy, r, startAngle, endAngle) {
var x1 = cx + r * Math.cos(-startAngle * rad),
x2 = cx + r * Math.cos(-endAngle * rad),
y1 = cy + r * Math.sin(-startAngle * rad),
y2 = cy + r * Math.sin(-endAngle * rad);
return ["M", x1, y1, "A", r, r, 0, +(endAngle - startAngle > 180), 0, x2, y2];
};
var zeroAngle = 197, fullAngle = -15,baseAngle = 199,
r = Raphael('level');
var level = r
.path(getCurvePath(150, 150, 75, zeroAngle, baseAngle))
.attr({
'stroke': '#FF0000',
'stroke-width': '11px'
});
window.setInterval(function() {
var ratio = Math.random();
var newLevelAngle = (zeroAngle - fullAngle) * ratio;
level.animate({
'path': getCurvePath(150, 150, 75, newLevelAngle, baseAngle)
}, 1000, 'bounce');
}, 2000);
I have set up a JS Fiddle here so you can see this in action: http://jsfiddle.net/Rfd3v/1/
The accepted answer here sorted my problem out:
drawing centered arcs in raphael js
I needed to adapt a few things from #genkilabs's answer to suit the level/gauge application. Hopefully this might be helpful to someone else:
var arcCentre = { x: 100, y: 100 },
arcRadius = 50,
arcMin = 1, // stops the arc disappearing for 0 values
baseRotation = -100, // this starts the arc from a different point
circleRatio = 220/360, // I found this helpful as my arc is never a full circle
maxValue = 1000; // arbitrary
// starts the arc at the minimum value
var myArc = r.path()
.attr({
"stroke": "#f00",
"stroke-width": 14,
arc: [arcCentre.x, arcCentre.y, arcMin, 100, arcRadius],
})
.transform('r'+ baseRotation + ',' + arcCentre.x + ',' + arcCentre.y);
// set a new value
var newValue = 234; // pick your new value
// convert value to ratio of the arc to complete
var ratio = newValue / maxValue;
// set level
var newLevelValue = Math.max(arcMin, ratio * 100 * circleRatio);
myArc.animate({
arc: [arcCentre.x, arcCentre.y, newLevelValue, 100, arcRadius]
}, 750, 'bounce');