Ricki Moore Ricki Moore - 1 year ago 60
Javascript Question

HTML5 Canvas increment x,y to origin(0,0) smoothly

Im trying to achieve a gravity like simulation where all points created on the canvas will return back to the origin(0,0)/or center of canvas from random generated spots on the canvas. Like stars sucked into black hole. How can i increment or decrement the x and y values so as they reach the destination at the same point? Now im adding or subtracting 1 (i also tried to decrement the bigger number slower) but im getting the x and y off so that it looks like the point hits a wall then drops or rises to the singularity.


var point = {
x: 615,
y: 215,
radius: 2

var singularity = {
x: 751,
y: 401,
radius: 2

Answer Source

Here's something I wrote for simple vector operations:

function vector(x, y) {

    this.x = x;
    this.y = y;
    var point = this;
    this.toString = function toString() {
        return point.x + "," + point.y;
    this.add = function (pos) {
        var x = point.x + pos.x;
        var y = point.y + pos.y;
        return new vector(x, y);
    this.subtract = function (pos) {
        var x = point.x - pos.x;
        var y = point.y - pos.y;
        return new vector(x, y);
    this.multiply = function multiply(scalar) {
        var x = point.x * scalar;
        var y = point.y * scalar;
        return new vector(x, y);
    this.magnitude = function magnitude() {
        return Math.sqrt(Math.pow(point.x, 2) + Math.pow(point.y, 2));
    this.unit = function unit() {
        var mag = point.magnitude();
        if (mag === 0)
            return point;
        return point.multiply(1 / mag);
    this.angle = function angle() {
        return Math.atan2(y, x);


You can use this to calculate the distance, direction and angle to the singularity;

var itemPosition = new vector(point.x, pointy);
var singularityPosition = new vector(singularity.x, singularity.y);
var displacementVector = singularityPosition.subtract(itemPosition);

var distanceFromSingluarity = displacementVector.magnitude();
var directionToSingularity = displacementVector.unit();

There might be some typos in there but it should get you started. Use the directionToSingularity.multiply(myCurrentSpeed) method in the vector object. It will give you a number you can add() to your pointVector to determine it's new location.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download