Chose scale in coordinate system - javascript

what I am currently trying to create is a coordinate system that visualizes some data. I don't want to use an existing framework, but would like to create it from scratch.
What I have are three points, e.g. (15, 20), (-5,1), (120,-17). They define the scale of the coordinate system with x-min = -5 and x-max = 120 and y-min = -17 and x-max = 20. This scale is what I cant quite find as it should be meaningful. In this example it wouldn't make sense to have the coordinate system reaching from (-100, -100) to (100,100) with one mark every 10.
<html>
<head>
<script type="text/javascript">
function drawShape(){
var canvas = document.getElementById('mycanvas');
if (canvas.getContext){
//draw canvas
var context = canvas.getContext('2d');
var canvasBorder = Math.floor(canvas.scrollHeight * 0.1);
var xLength = Math.floor(canvas.scrollWidth - (canvasBorder * 2));
var yLength = Math.floor(canvas.scrollHeight - (canvasBorder * 2));
//draw coordinate system
context.beginPath();
context.moveTo(canvasBorder, canvasBorder); //30,30
context.lineTo(canvasBorder, canvasBorder + yLength); //30,270
context.lineTo(canvasBorder + xLength, canvasBorder + yLength); //370,30
context.stroke();
//easy: define 5 values for x-axis
var xMaxValue = 5;
var tmp = Math.floor(xLength / xMaxValue);
for(i = 0; i <= xMaxValue; i++){
context.beginPath();
context.moveTo(canvasBorder + tmp*i, canvasBorder + yLength);
context.lineTo(canvasBorder + tmp*i, canvasBorder + yLength+10);
context.fillText(i, canvasBorder + tmp*i, canvasBorder + yLength+10);
context.stroke();
}
//difficult: have a max value for y-axis
//too much space between 117 and 200, should display 120 or 150 instead
//next level, what happens with -20 instead of 0 for min-y
var yMaxValue = 117;
var yIncrement = Math.pow(10, (Math.abs(Math.floor(yMaxValue)).toString().length)) / 10;
var topValue = Math.floor(yMaxValue / yIncrement) + 1;
var tmp = parseInt(yLength / topValue);
for(i = 0; i <= topValue; i++){
context.beginPath();
context.moveTo(canvasBorder, yLength + canvasBorder - tmp*i);
context.lineTo(canvasBorder - 10, yLength + canvasBorder - tmp*i);
context.fillText(yIncrement * i, canvasBorder - 10, yLength + canvasBorder - tmp*i);
context.stroke();
}
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body onload="drawShape();">
<canvas id="mycanvas" width="400" height="300"
style="border:1px solid #ddd;">
</canvas>
</body>
</html>
Or is there a better way to take data create a coordinate system accordingly?
Cheers,
Florian

Sounds like you want to map your actual values into a more traditional range for display on your chart.
For example, assume:
Your actual values range from -17 to 120.
You want to map these actual values into a more traditional range of 0 to 100.
Here's a function that maps a value from your actual range into a different range.
function remap(value, actualMin, actualMax, newMin, newMax) {
return(newMin + (newMax - newMin) * (value - actualMin) / (actualMax - actualMin);
}
For example, to remap your actual value of 33 (range -17 to 120) into the range of 0-100:
remappedValue = remap( 33, -17,120, 0,100 );
Note that the example new range of 0-100 is just an example.
You could use any range you desire for newMin to newMax.

Related

Numbers that result in a more rounded corner when graphing in Javascript

I have a for loop that returns a decimal between 0 and 1. I'd like to make a curve that appears more like a rounded corner than it is now. I'd also like to have it start ramping up only after 0.25. I can't quite figure out how to do it with the math I have now. I'm using Math.log and a linear conversion function, but maybe I need something more related to a parabolic curve.
for (i = 1; i < 101; ++i) {
var dec = i / 100
if (dec >= 0.25) {
console.log("dec = " + dec);
var large = i * 100
var log = Math.log(large);
console.log("log = " + log);
var linCon = applyLinearConversion(log, 2.8, 9.2104, -2.7, 1)
console.log("linCon " + i + " = " + linCon);
document.getElementById("graph").innerHTML += "<div style='background-color:#000000; width:" + (linCon * 1000) + "px; height:5px;'></div>";
}
}
function applyLinearConversion(OldValue, OldMin, OldMax, NewMin, NewMax) {
OldRange = (OldMax - OldMin)
if (OldRange == 0)
NewValue = NewMin
else {
NewRange = (NewMax - NewMin)
NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin
}
return NewValue
}
<div id="graph"></div>
I have it populating a div with more styled divs.
Mine is like this:
I want mine more like this:
You can use the formula of the half circle graph which is:
It results in the following graph:
Since you are using horizontal divs that are stacked vertically to draw the graph, the x and y coordinates will be reversed and the left quarter of the circle will be used from the above graph.
var width = 200; // the width of the graph
var height = 200; // the height of the graph
var xOffset = 0.25 * width; // the x offset at which the graph will start ramping up (this offset is added to the graph width)
var html = ""; // to accumulate the generated html before assigning it to innerHTML (it's not a good idea to constantly update innerHTML)
for (i = 1; i < 101; ++i) {
var x = 1 - i / 100; // the x coordinate, we are using the left side of the graph so x should be negative going from -1 to 0
var y = Math.sqrt(1 - x * x); // the y coordinate as per the formula (this will be used for the width)
html += "<div style='background-color:#000000; width:" + (xOffset + y * width) + "px; height:" + (height / 100) + "px;'></div>";
}
document.getElementById("graph").innerHTML = html;
<div id="graph"></div>

Canvas animation with JavaScript. Random coordinates and speed at every initiation

Edited : Thanks to all for valuable time and effort. Finally I made this )) JSfiddle
I was just playing with canvas and made this. Fiddle link here.
... some code here ...
var cords = [];
for(var i = 50; i <= width; i += 100) {
for(var j = 50; j <= height; j += 100) {
cords.push({ cor: i+','+j});
}
}
console.log(cords);
var offset = 15,
speed = 0.01,
angle = 0.01;
cords.forEach(function(e1) {
e1.base = parseInt(Math.random()*25);
e1.rgb = 'rgb('+parseInt(Math.random()*255)+','+parseInt(Math.random()*255)+','+parseInt(Math.random()*255)+')';
});
setInterval(function() {
cords.forEach(function(e1) {
e1.base = parseInt(Math.random()*25);
e1.rgb = 'rgb('+parseInt(Math.random()*255)+','+parseInt(Math.random()*255)+','+parseInt(Math.random()*255)+')';
});
},5000);
function render() {
ctx.clearRect(0,0,width,height);
cords.forEach(function(e1) {
//console.log(e1);
ctx.fillStyle = e1.rgb;
ctx.beginPath();
var r = e1.base + Math.abs(Math.sin(angle)) * offset;
var v = e1.cor.split(',');
ctx.arc(v[0],v[1],r,0,Math.PI * 2, false);
ctx.fill();
});
angle += speed;
requestAnimationFrame(render);
}
render();
Was wondering if -
Coordinates can be made random, now they are fixed as you can see. After 5000 mil, balls will show up in various random cords but even at their fullest they won't touch each other.
Every ball has same speed for changing size, I want that to be different too. Meaning, After 5000 mil, they show up with different animation speeds as well.
Also any suggestion on improving code and making it better/quicker/lighter is much appreciated. Thank you !
TL;DR - See it running here.
Making the coordinates random:
This requires you to add some random displacement to the x and y coordinates. So I added a random value to the coordinates. But then a displacement of less than 1 is not noticeable. So you'd need to magnify that random number by a multiplier. That's where the randomizationFactor comes in. I have set it to 100 since that is the value by which you shift the coordinates in each iteration. So that gives a truly random look to the animation.
Making Speed Random:
This one took me a while to figure out, but the ideal way is to push a value of speed into the array of coordinates. This let's you ensure that for the duration of animation, the speed will remain constant and that gives you a smoother feel. But again multiplying the radius r with a value between 0 and 1 reduces the speed significantly for some of the circles. So I have added a multiplier to 3 to compensate slightly for that.
Ideally I'd put a 2, as the average value of Math.random() is 0.5, so a multiplier of 2 would be adequate to compensate for that. But a little experimentation showed that the multiplier of 3 was much better. You can choose the value as per your preference.
Your logic of generating the coordinates changes as follows:
for(var i = 50; i <= width;i += 100) {
for(var j = 51; j <= height;j += 100) {
var x = i + (Math.random() - 0.5)*randomizationFactor;
var y = j + (Math.random() - 0.5)*randomizationFactor;
cords.push({ cor: x+','+y, speed: Math.random()});
}
}
Your logic of enlarging the circles changes as follows:
function render() {
ctx.clearRect(0,0,width,height);
cords.forEach(function(e1) {
//console.log(e1);
ctx.fillStyle = e1.rgb;
ctx.beginPath();
var r = e1.base + Math.abs(Math.sin(angle)) * offset * e1.speed * 3;
var v = e1.cor.split(',');
ctx.arc(v[0],v[1],r,0,Math.PI * 2, false);
ctx.fill();
});
angle += speed ;
requestAnimationFrame(render);
}
Suggestion: Update the coordinates with color
I'd probably also update the location of circles every 5 seconds along with the colors. It's pretty simple to do as well. Here I've just created a function resetCoordinates that runs every 5 seconds along with the setBaseRgb function.
var cords = [];
function resetCoordinates() {
cords = [];
for(var i = 50; i <= width;i += 100) {
for(var j = 51; j <= height;j += 100) {
var x = i + (Math.random() - 0.5)*randomizationFactor;
var y = j + (Math.random() - 0.5)*randomizationFactor;
cords.push({ cor: x+','+y, speed: Math.random()});
}
}
}
UPDATE I did some fixes in your code that can make your animation more dynamic. Totally rewritten sample.
(sorry for variable name changing, imo now better)
Built in Math.random not really random, and becomes obvious when you meet animations. Try to use this random-js lib.
var randEngine = Random.engines.mt19937().autoSeed();
var rand = function(from, to){
return Random.integer(from, to)(randEngine)
}
Internal base properties to each circle would be better(more dynamic).
var circles = [];
// better to save coords as object neither as string
for(var i = 50; i <= width; i += 100)
for(var j = 50; j <= height; j += 100)
circles.push({
coords: {x:i,y:j}
});
We can adjust animation with new bouncing property.
var offset = 15,
speed = 0.005,
angle = 0.01,
bouncing = 25;
This is how setBaseRgb function may look like
function setBaseRgb(el){
el.base = rand(-bouncing, bouncing);
el.speed = rand(5, 10) * speed;
el.angle = 0;
el.rgb = 'rgb('+rand(0, 255)+','+rand(0, 255)+','+rand(0, 255)+')';
}
All your animations had fixed setInterval timeout. Better with random timeout.
cords.forEach(function(el){
// random timeout for each circle
setInterval(setBaseRgb.bind(null,el), rand(3000, 5000));
})
You forgot to add your base to your circle position
function render() {
ctx.clearRect(0,0,width,height);
circles.forEach(function(el) {
ctx.fillStyle = el.rgb;
ctx.beginPath();
var r = bouncing + el.base + Math.abs(Math.sin(el.angle)) * offset;
var coords = el.coords;
ctx.arc(
coords.x + el.base,
coords.y + el.base,
r, 0, Math.PI * 2, false
);
ctx.fill();
el.angle += el.speed;
});
requestAnimationFrame(render);
}
render();
Effect 1 JSFiddle
Adding this
if(el.angle > 1)
el.angle=0;
Results bubling effect
Effect 2 JSFiddle
Playing with formulas results this
Effect 3 JSFiddle

Calculate current position between two points based on distance left

Ok, I have two positions in 3d space:
var fromX = 1,
fromY = 2,
fromZ = 3,
toX = 15,
toY = 16,
toZ = 17;
Then I need to calculate the current position, when someone/something is moving in a straight line from the from-coordinates, to the to-coordinates. I know the distance left is 2, what would be the formula for calculating the current position?
I guess this is more of a math question than a javascript question, but it is for a javascript application, so I'm hoping that is not a problem.
Given two points, fromPt and toPt, the distance between two points can easily be calculated:
distanceX = Math.pow(fromPt.x - toPt.x, 2)
distanceY = Math.pow(fromPt.y - toPt.y, 2)
distanceZ = Math.pow(fromPt.z - toPt.z, 2)
total_distance = Math.sqrt(distanceX + distanceY + distanceZ)
and now finding the correct point along the line is just a case of correct interpolation :)
newPt = {}
newPt.x = fromPt.x + ((toPt.x - fromPt.x) * (wantedDistance / total_distance))
newPt.y = fromPt.y + ((toPt.y - fromPt.y) * (wantedDistance / total_distance))
newPt.z = fromPt.z + ((toPt.z - fromPt.z) * (wantedDistance / total_distance))
There are already 2 answers with the correct algorithm, this one's no different, just a bit neater.
// Distance between two points is the square root of the sum
// of the squares of the differences
function get3dDistance(startCoords, endCoords) {
var dx = Math.pow((startCoords[0] - endCoords[0]), 2);
var dy = Math.pow((startCoords[1] - endCoords[1]), 2);
var dz = Math.pow((startCoords[2] - endCoords[2]), 2);
return Math.sqrt(dx + dy + dz);
}
// The coordinates of a point some distance from the end is
// proportional to the distance left and total distance.
function getCoordsFromDistanceLeft(startCoords, endCoords, distanceLeft) {
var distance = get3dDistance(startCoords, endCoords);
var f = (distance - distanceLeft)/distance;
return [startCoords[0] + f*(endCoords[0] - startCoords[0]),
startCoords[1] + f*(endCoords[1] - startCoords[1]),
startCoords[2] + f*(endCoords[2] - startCoords[2])];
}
// Test case
var start = [1,2,3];
var end = [15,16,17];
var distanceLeft = 2;
// Distance between the two points
var dist = get3dDistance(start, end)
document.write('distance: ' + dist + '<br>');
// distance: 24.24871130596428
// Get the coords
var x = getCoordsFromDistanceLeft(start, end, distanceLeft);
document.write('x: ' + x + ' is ' + distanceLeft + ' to end<br>');
// x: 13.845299461620748,14.845299461620748,15.845299461620748 is 2 to end
document.write('From x to end: ' + get3dDistance(x, end) + '<br>');
// From x to end: 2.0000000000000013
Salix alba has introduced Math.hypot, which is interesting but since it's a new feature in ECMAScript 2015 it would be wise to include a polyfill.
You need to use 3D Pythagoras to find the distance between two points. If x1,y1,z1 and x2,y2,z2 are your points then the distance is sqrt((x1-x2)^2+(y1-y2)^2+(z1-z2)^2). There are several ways of finding the desired point. We can find the distance from the starting point to the ending point and then calculate the proportion of that distance which will give 2 as a result using linear interpolation.
var fromX = 1,
fromY = 2,
fromZ = 3,
toX = 15,
toY = 16,
toZ = 17;
// find the difference
var dx = toX-fromX, dy = toY-fromY, dz=toZ-fromZ;
// find the total length
var dist = Math.hypot(dx,dy,dz);
// find the proportion of this length
var lambda = (dist-2.0) / dist;
// do the linear interpolation
var x = fromX + lambda * dx,
y = fromY + lambda * dy,
z = fromZ + lambda * dz;
console.log(x,y,z);
// Just to check
var dx2 = toX-x, dy2 = toY-y, dz2=toZ-z;
var dist2 = Math.hypot(dx2,dy2,dz2);
console.log(dist2);
We get the result 13.845299461620748 14.845299461620748 15.845299461620748 and the final distance is 2.0000000000000013.
Note I've uses Math.hypot this is a new feature which works in Chrome/firefox/opera but not in IE. There is a work-around to enable it in other browsers if needed. You just use Math.sqrt(dx*dx+dy*dy+dz*dz) instead.

Rotating a clock hand in javascript

I am learning to make a clock using raphael js,
I am using this tutorial to get me started http://www.tuttoaster.com/creating-a-clock-animation-without-css3/
When this is diplayed the second hand doesnt move one second per second. I know one second is 6 degrees, it moves around 45 degrees though!
If someone could please explain what he has done wrong and how to make the hands rotate at appropriate angles that would be great. I am a beginner so plain english please :)
The code is as follows.
window.onload = function(){
var canvas = Raphael("pane",0,0,500,500);
canvas.circle(200,150,100).attr("stroke-width",2);
canvas.circle(200,150,3).attr("fill","#000");
var angleplus = 360,rad = Math.PI / 180,
cx = 200,cy =150 ,r = 90,
startangle = -90,angle=30,x,y, endangle;
for(i=1;i<13;i++)
{
endangle = startangle + angle ;
x = cx + r * Math.cos(endangle * rad);
y = cy + r * Math.sin(endangle * rad);
canvas.text(x,y,i+"");
startangle = endangle;
}
var hand = canvas.path("M200 70L200 150").attr("stroke-width",1);
var minute_hand = canvas.path("M200 100L200 150").attr("stroke-width",2);
var hour_hand = canvas.path("M200 110L200 150").attr("stroke-width",3);
var time = new Date();
angle = time.getSeconds() * 6;
minute_hand.rotate(6 * time.getMinutes(),200,150);
var hr = time.getHours();
if(hr>12)
hr = hr -11;
hour_hand.rotate(30 * hr,200,150);
var minute_angle= 6 + time.getMinutes()*6,hour_angle=0.5+
time.getMinutes()*30;
setInterval(function(){
angle = angle + 6;
if(angle>=360)
{
angle=0;
minute_hand.rotate(minute_angle,200,150);
minute_angle = minute_angle + 6;
hour_hand.rotate(hour_angle,200,150);
hour_angle = hour_angle + 0.5;
}
if(minute_angle>=360)
{
minute_angle=0;
}
hand.rotate(angle,200,150);
},1000);
hand.rotate(6,200,150);
Bernard, you don't need to rotate by the variable angle since you're simply rotating by 6 degrees every second regardless of how many seconds have elapsed.
http://jsbin.com/domoqojipe/1/
So you want to speed up the clock speed by twenty?
It's a long shot, but try changing the 1000 at the bottom to 50. Because 1000 divided by 20 equals 50.
Try that and see if it works...

How to connect the dots ? (the dots are randomly positioned HTML elements)

I'm using the following code to generate random points with a maximum distance from another element I have in the page:
function drawPoints (maxdistance, npoints) {
var start = $('#startingPoint').position();
var draw = document.getElementById('draw');
var i = npoints;
while(i--) {
var n = document.createElement('div');
n.style.position = 'absolute';
n.style.top = ( - (Math.random() * maxdistance) -10 + start.top).toString() + 'px';
n.style.left = ( - (Math.random() * maxdistance) + 50 + start.left).toString() + 'px';
n.style.width = '6px';
n.style.height = '6px';
n.style.backgroundColor = 'black';
n.style.borderRadius = '6px';
draw.appendChild(n);
}
}
For an example, drawPoints(150, 20); would draw 20 points with a maximum distance of 150 from the starting point.
The question is, how do I draw some kind of arcs or lines to connect some of this dots ?
Using the canvas and other new features is very good, but I think that almost ALL things can be re-programmed with very simple built-in functions (and of course without jQuery).
This is a cross-browser function to connect the dots:
function connectDots(xA,yA,xB,yB)
{
var a=document.createElement("div");
var r=180*Math.atan2(yB-yA,xB-xA)/Math.PI;
a.setAttribute("style","width:"+Math.sqrt(Math.pow(xA-xB,2)+Math.pow(yA-yB,2))+"px;height:1px;position:absolute;background-color:black;top:"+yA+"px;left:"+xA+"px;-moz-transform:rotate("+r+"deg);-moz-transform-origin:0px 0px;-webkit-transform:rotate("+r+"deg);-webkit-transform-origin:0px 0px;transform:rotate("+r+"deg);transform-origin:0px 0px;-ms-transform:rotate("+r+"deg);-ms-transform-origin:0px 0px;");
document.body.appendChild(a);
}
Four lines.
Fiddle: http://jsfiddle.net/mageek/3aG5H/2/

Categories