0

I have the following code:

https://jsfiddle.net/8o3sn9mh/21/

var
    canvas = document.getElementById('c'),
    ctx = canvas.getContext('2d');
    width = window.innerWidth;
    height = window.innerHeight;
    canvas.width = width;
    canvas.height = height;
    thrust = height * 0.000001;
    maxVelocity = height * 0.00067;
    velocity = height * 0.00019;

    velocityInterval = setInterval(function(){
                velocity+= thrust;
                if(velocity > maxVelocity) velocity = maxVelocity;
                ctx.fillRect(1, height / 2, width * (velocity / maxVelocity), height / 30);
    }, 1);

explanation: I have a canvas which adapts to the user's window. I am trying to represent speed progress upon the canvas with the following starting parameters: velocity, Max velocity(speed limit) and thrust which accelerates the velocity every millisecond.

the bar starts accelerating from a certain velocity(0.00019) and when you reach full speed the bar's width is exactly the canvas' width. it works fine but as you can see the graph bar starts at a certain x point which is not 0x, because i decided that the starting velocity shall be quite fast. how can I start the bar at 0x and still be accurate with the speed progress?

here is how it should look like(of course the logic i was talking about is not included here):

https://jsfiddle.net/8o3sn9mh/33/

user1938653
  • 611
  • 1
  • 9
  • 21

1 Answers1

0

You can re-map the value between 0 and max. Javascript has no native build in function for that.

But you can take one from p5 library for example which is:

Math.map = function (value, istart, istop, ostart, ostop) {
    return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));
}

Or follow this discussion on SO.

This function re-maps a value to a new range.

So in your case you'd define

var mapStart = width* ((height * 0.00019)/maxVelocity);

and map the (velocity,width) calculation to be between 0 and max. width

var mappedValue = Math.map((width * (velocity / maxVelocity)), mapStart, width, 0, width);
ctx.fillRect(1, height / 2, mappedValue, height / 30);

The fiddle.

Community
  • 1
  • 1
michaPau
  • 1,598
  • 18
  • 24