This is what I have right now:
I want to make it like this:
The blue line as you can see passes through the center(400,400). The start of the blue line is not fixed, it moves according to data that the user enter.
How do I add this blue line and make it pass through the center?
Sorry for my bad English, working on that :)
Halfon
Use mathematics.
Let the center co-ordinates be (Cx, Cy), which in your case are (400, 400). Let the user's co-ordinates be (Ux, Uy).
The equation of the line passing through the center from (Ux, Uy) would be given by the equation:
y - Cy = slope * (x - Cx), where slope = (Cy - Uy) / (Cx - Ux).
Now, to draw the line from Ux to some x co-ordinate, say Px, simply use the equation to calculate Py = Slope * (Px - Cx) + Cy, then draw the line from (Ux, Uy) to (Px, Py).
context.beginPath();
context.moveTo(Ux, Uy);
context.lineTo(Px, Py);
context.stroke();
Simply draw the line through the center point and extend its length. It's completely unclear what the length of the line is because you failed to provide any code, so I'm just doubling it in the example.
To calculate the end points, just subtract the starting x/y coordinates from the doubled x/y coordinates of the central point.
I wrote you a dynamic example which takes the mouse coordinates as a starting position, but the same principle applies if you only have a single static point from the user input. Try it here:
var canvas = document.getElementById('c');
var context = canvas.getContext('2d');
var centerPoint;
function setSize() {
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
centerPoint = {x: canvas.width / 2, y: canvas.height / 2};
}
canvas.addEventListener('mousemove', function(e) {
canvas.width = canvas.width;
context.beginPath();
context.moveTo(e.offsetX, e.offsetY);
context.lineTo(centerPoint.x * 2 - e.offsetX, centerPoint.y * 2 - e.offsetY);
context.lineWidth = 3;
context.strokeStyle = '#0000ff';
context.stroke();
})
canvas.addEventListener('mousedown', function(e) {
centerPoint = {x: e.offsetX, y: e.offsetY};
canvas.width = canvas.width;
})
window.addEventListener('resize', setSize);
setSize()
canvas {width: 100%;height: 100%;position: absolute;}
body {margin: 0}
p {position: absolute; pointer-events: none}
<canvas id="c"></canvas>
<p>Click anywhere to set the center point (dead center by default)</p>
Related
I have an instance of HTML 5 canvas and a rectangle drawn on it.
My drawing function takes a resizing angle into account and uses relative coordinates.
Relative coordinates're based upon three variables: top left rectangle point, rectangle width and rectangle height.
Rectangle width and rectangle height're calculated using two points: top left rectangle point and bottom right rectangle point.
To sum up, drawing function depends on top left rectangle point, bottom right rectangle point and rotation. It's an important point for the following text!
Here's a code snippet:
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');
var xTopLeft = 550;
var yTopLeft = 200;
var xBottomRight = 750;
var yBottomRight = 450;
var w = Math.max(xTopLeft, xBottomRight) - Math.min(xTopLeft, xBottomRight);
var h = Math.max(yTopLeft, yBottomRight) - Math.min(yTopLeft, yBottomRight);
var r = 1;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save()
ctx.translate(xTopLeft + w / 2, yTopLeft + h / 2);
ctx.rotate(r);
ctx.fillStyle = "yellow";
ctx.fillRect(w / 2 * (-1), h / 2 * (-1), w, h);
ctx.restore()
}
Here's my rectangle with a bunch of controls: eight resizing handles (white) and one rotation handle (green):
Rotating works fine.
Resizing works fine.
And I also try to implement resizing after rotation. Here's my approach with a humble illustration:
Grab the coordinates of the red point (it's mouse cursor coordiantes)
Derotate the point using negative angle to get derotated coordinates
function rotatePoint(x, y, center_x, center_y, angle) {
var new_x = (x - cx) * Math.cos(angle) - (y - cy) * Math.sin(angle) + cx;
var new_y = (x - cx) * Math.sin(angle) + (y - cy) * Math.cos(angle) + cy;
return [new_x, new_y]
}
Update xTopLeft, yTopLeft and redraw
Done
The idea behind this approach is simple. Since my drawing function depeneds on top left rectangle point and bottom right rectangle point I just need to get their new coordinates.
For instance, here's a simplified code for B point:
if (point == 'B') {
var newPointB = rotatePoint(mouse.x, mouse.y, center_x, center_y, -r);
xBottomRight = newPointB[0];
yTopLeft = newPointB[1];
}
But it doesn't work as expected: while resizing my rotated rectangle shifts, jumps and totally misbehaves.
In search of insights I've stumbled upon this article. The article covers my problem, but I don't get author's approach and can't implement it.
Why should I always lock the coordinates of the A point? My top left handle is intended to resize the rectangle in a north-west direction, so it would be necessary to change the coordinates of the A point...
Why should we recalculate the center point before derotation? It breaks the idea of uniform matrix transformations...
What's the correct algorithm in my case?
I was also facing same problem. It turned out that the angle I was using was in degree. Try multiplying angle in rotatePoint function with (Math.PI / 180).
Let's say we're dynamically drawing a fractal on a canvas. Since we don't know how big the fractal is going to be, at some point we'd need to scale (zoom out) the canvas to fit our fractal in there.
How do we do that? How to scale it:
Properly, so that it perfectly fits the drawing we have, and
So that the coordinates stay the same, and our fractal calculation doesn't need to use the scale value (meaning, return x, not return x * scale, if possible)
What if the fractal grows in all directions and we have negative values?
See the tiny example below.
var $canvas = document.querySelector('canvas'),
ctx = $canvas.getContext('2d'),
lastX = 0,
lastY = 0;
drawLoop();
function drawLoop() {
var newX = lastX + 30,
newY = lastY + 30;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(newX, newY);
ctx.stroke();
lastX = newX;
lastY = newY;
setTimeout(drawLoop, 1000);
}
<canvas width="100" height="100" style="border: 1px solid #ccc;"></canvas>
You can scale, translate, and rotate the drawing coordinates via the canvas transform.
If you have the min and max coordinates of your drawing
Example:
const min = {x: 100, y: 200};
const max = {x: 10009, y: 10000};
You can make it fit the canvas as follows
const width = canvas.width;
const height = canvas.height;
// get a scale to best fit the canvas
const scale = Math.min(width / (max.x - min.x), height / (max.y - min.y));
// get a origin so that the drawing is centered on the canvas
const top = (height - (max.y - min.y)) / 2;
const left = (width - (max.x - min.x)) / 2;
// set the transform so that you can draw to the canvas
ctx.setTransform(scale, 0, 0, scale, left, top);
// draw something
ctx.strokeRect(min.x, min.y, max.x - min.x, max.y - min.y);
If you do not know the size of the drawing area at the start then you will need to save drawing coordinates as you go. When the min and max change you then recalculate the transform, clear the canvas and redraw. There is no other way if you do not know the size at the beginning.
I'm using CSS to try and create a label (which is a popup that always remains on the map) attached to a circle. The following link will lead to the image of what I'm trying to do: Image. In order to achieve this I've been using the following code:
$(popup._container.firstChild).css({
background: "-webkit-radial-gradient(-29px" + percentZoom + ", circle closest-corner, rgba(0, 0, 0, 0) 0, rgba(0, 0, 0, 0) 58px, white 59px)"
});
Before, I was calculating the percentZoom depending on the radius of the circle and the zoom where the map is now.
var percent = (50 * presentCircleRadius) / 300000 //when the radius is 300000 the percentage should be 50%
var percentZoom = (percent * zoom) / 6; // then calculate it the exact zoom that should be used depending on the zoom. Being 6 the default one.
This didn't work or it had many issues when I zoomed in on the map (considering that the circle doesn't really change but the curvature seems to becoming flatter).
I tried using canvas as well to get the result that I wanted it, but I had issues. I was using two arches to build the top part and the bottom part, then thought about using two rectangles to create the two parts to the right of the circle. The problem with this it's that the circle is transparent and it's meant to start on the edge of it, if I used this solution the rectangle would appear in the middle of the circle.
var canvas = document.getElementById('myCanvas1');
var context = canvas.getContext('2d');
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 75;
var startAngle = 1.1 * Math.PI;
var endAngle = 1.9 * Math.PI;
var counterClockwise = false;
context.beginPath();
context.arc(x, y, radius, 1.6 * Math.PI, 0 * Math.PI, counterClockwise);
context.lineWidth = 15;
// line color
context.strokeStyle = 'black';
context.stroke();
context.beginPath();
context.arc(x, y, radius, 0 * Math.PI, 0.4 * Math.PI, counterClockwise);
context.lineWidth = 15;
// line color
context.strokeStyle = 'red';
context.stroke();
context.beginPath();
context.lineWidth = "10";
context.strokeStyle = "blue";
context.rect(x, y - radius, 150, radius);
context.stroke();
<canvas id="myCanvas1" width="578" height="250"></canvas>
So I thought of using lines instead of rectangles to create the right part of the label: fiddle, the problem with this solution is, as mention before, as you zoom the curvature will change and I found no way to calculate exactly where the lines on the top and on the bottom should start.
Is there a way to do what I want to do: Make it so that the label follows the curvature of the circle as you zoom in and out and if so how can I make it so considering that there might be more than one circle per zoom with different radius?
Is it possible to make an object orbit around another object that goes from behind and then to the front?
I've seen it being done with rotation animations that do a full 360 around the perimeter, but was wondering if it was possible to do it at an angle.
I couldn't find any resources that could do this, so I've included an image example of what I want to accomplish. The red line would be an object orbiting the blue circle.
Thanks so much - I really appreciate the help!
I figured I'd just write up a solution using the <canvas>
var x, y, scale, state, // Variables we'll use later.
canvas = document.getElementById("canvas"), // Get the canvas,
ctx = canvas.getContext("2d"), // And it's context.
counter = 0, // Counter to increment for the sin / cos functions.
width = 350, // Canvas width.
height = 200, // Canvas height.
centerX = width / 2, // X-axis center position.
centerY = height / 2, // Y-axis center position.
orbit = { // Settings for the orbiting planet:
width: 150, // Orbit width,
height: 50, // Orbit height,
size: 10 // Orbiting planet's size.
};
canvas.width = width; // Set the width and height of the canvas.
canvas.height = height;
function update(){
state = counter / 75; // Decrease the speed of the planet for a nice smooth animation.
x = centerX + Math.sin(state) * orbit.width; // Orbiting planet x position.
y = centerY + Math.cos(state) * orbit.height; // Orbiting planet y position.
scale = (Math.cos(state) + 2) * orbit.size; // Orbiting planet size.
ctx.clearRect(0, 0, width, height); // Clear the canvas
// If the orbiting planet is before the center one, draw the center one first.
(y > centerY) && drawPlanet();
drawPlanet("#f00", x, y, scale); // Draw the orbiting planet.
(y <= centerY) && drawPlanet();
counter++;
}
// Draw a planet. Without parameters, this will draw a black planet at the center.
function drawPlanet(color, x, y, size){
ctx.fillStyle = color || "#000";
ctx.beginPath();
ctx.arc(x || centerX,
y || centerY,
size || 50,
0,
Math.PI * 2);
ctx.fill();
}
// Execute `update` every 10 ms.
setInterval(update, 10);
<canvas id="canvas"></canvas>
If you want to change the roation direction of the orbiting planet, just replace:
x = centerX + Math.sin(state) * orbit.width;
y = centerY + Math.cos(state) * orbit.height;
With:
x = centerX + Math.cos(state) * orbit.width;
y = centerY + Math.sin(state) * orbit.height;
// ^ Those got switched.
The speed of the orbit can be changed by modifying the 75 in:
state = counter / 75;
Here is an example!
I am trying to reset the green arc inside drawValueArc() so that each time you click the change button, the green arc is removed and redrawn. How can I remove it without removing the entire canvas? Also, as an aside, I have noticed that Math.random() * 405 * Math.PI / 180 doesn't actually always result in an arc that fits inside the gray arc, sometimes it is larger than the gray arc, why is this?
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cx = 150;
var cy = 150;
var startRadians = 135 * Math.PI / 180;
var endRadians = 405 * Math.PI / 180;
//main arc
ctx.beginPath();
ctx.arc(cx, cy, 58, startRadians, endRadians, false);
ctx.strokeStyle="rgb(220,220,220)";
ctx.lineWidth = 38;
ctx.stroke();
$('#setRandomValue').click(function(){
drawValueArc(Math.random() * 405 * Math.PI / 180);
});
function drawValueArc(val){
//ctx.clearRect(0, 0, W, H);
ctx.beginPath();
ctx.arc(cx, cy, 58, startRadians, val, false);
ctx.strokeStyle = "green";
ctx.lineWidth = 38;
ctx.stroke();
}
Drawing past boundary
The problem you are facing is in first instance the fact you are drawing before and after a 0-degree on the circle. This can be complicated to handle as you need to split in two draws: one for the part up to 0 (360) and one 0 to the remaining part.
There is a simple trick you can use to make this easier to deal with and that is to deal with all angles from 0 and use an offset when you draw.
Demo using redraw base (I moved it to jsfiddle as jsbin did not work for me):
http://jsfiddle.net/3dGLR/
Demo using off-screen canvas
http://jsfiddle.net/AbdiasSoftware/Dg9Jj/
First, some optimizations and settings for the offset:
var startRadians = 0; //just deal with angles
var endRadians = 300;
var deg2rad = Math.PI / 180; //pre-calculate this to save some cpu cycles
var offset = 122; //adjust this to modify rotation
We will now let the main function, drawArc() do all calculations for us so we can focus on the numbers - here we also offset the values:
function drawArc(color, start, end) {
ctx.beginPath();
ctx.arc(cx, cy, 58,
(startRadians + offset) * deg2rad,
(end + offset) * deg2rad, false);
ctx.strokeStyle = color;
ctx.lineWidth = 38;
ctx.stroke();
}
Clearing the previous arc
There are several techniques to clear the previous drawn arc:
You can draw the base arc to an off-screen canvas and use drawImage() to erase the old.
You can do as in the following example, just re-draw it with the base color
As with 2. but subtracting the green arc and draw the base color from the end of the green arc to the end of the base arc.
clearing the whole canvas with fillRect or clearRect.
1 and 3 are the fastest, while 4 is the slowest.
With out re-factored function (drawArc) it's as easy as this:
function drawValueArc(val) {
drawArc("rgb(220,220,220)", startRadians, endRadians);
drawArc("green", startRadians, val);
}
As everything now is 0-based concerning start we really don't need to give any other argument than 0 to the drawArc instead of startRadians. Use the new offset to offset the start position and adjust the endRadians to where you want it to stop.
As you can see in the demo, using this technique keeps everything in check without the need to draw in split.
Tip: if you notice green artifacts on the edges: this is due to anti-alias. Simply reduce the line width for the green color by 2 pixels (see demo 2, off-screen canvas).