Skip to content Skip to sidebar Skip to footer

Calculate The X, Y Position Of A Canvas Point

I'm trying to learn some canvas in html5 and javascript and I want to create those typical Illustrator sun rays: But my problem is that I want to automate it and make it full scre

Solution 1:

It seems like you should use the trig functions to do something like this.

var coordinate_array = [];
var xCoord = 0;
var yCoord = 0;
var angleIncrement = 15;
var i = 0;

//iterate over angles (in degrees) from 0 to 360for (var theta = 0; theta < 360; theta += angleIncrement) {
    //angle is in sector from bottom right to top right cornerif (theta >= 315 || theta <= 45) 
    {
        xCoord = $(window).width();//point on right side of canvas
        yCoord = abs($(window).width()/2 * tan(theta));
        yCoord = tranformY(theta,yCoord);
    } 
    //angle is in sector from top right to top left cornerelseif (theta > 45 && theta <= 135) 
    {
        yCoord = 0; //top is zero 
        xCoord = abs($(window).height()/2 * tan(theta));
        xCoord = transformX(theta, xCoord);
    } 
    //angle is in sector from top left to bottom left cornerelseif (theta > 135 && theta <= 225) 
    {
        xCoord = 0; //left edge on a canvas is zero
        yCoord = abs($(window).width()/2 * tan(theta);
        yCoord = transformY(theta, yCoord);
    }
    //angle is in sector from bottom left to bottom right cornerelse// theta > 225 && theta < 315
    {
        yCoord = $(window).height();
        xCoord = abs($(window).height()/2 * tan(theta));
        xCoord = transformX(theta, xCoord);
    }
    coordinate_array[i++] = newArray(xCoord, yCoord);        
}

//Transform from cartesian coordinates to top left is 0,0functiontranformY(theta, y)
{
  var centerYCoord = $(window).height()/2;
  //if angle falls in top half (Quadrant 1 or 2)if(theta > 0 && theta < 180)
  {
    return centerYCoord - y;
  }
  elseif(theta > 180 && theta < 360)
  {
    return centerYCoord + y;
  }
  //coord falls on 0/360 or 180 (vert. median)return centerYCoord;
}

//Transform from cartesian coordinates to top left is 0,0functiontransformX(theta, x)
{
  var centerXCoord = $(window).width()/2;
  //if angle falls in right half (Quadrant 1 or 4)if(theta > 270 || theta < 90)
  {
    return centerXCoord + x;
  }
  elseif(theta > 90 && theta < 270)      
  {
    return centerXCoord - x;
  }
  //coordinate falls on 270 or 90 (center)return centerXCoord;
}

 //now draw your rays from the center coordinates to the points in coordinate_array//NOTE: This code will need to be cleaned up - I just wrote it in the textbox.

Solution 2:

Coordintate Points

The previous code puts the coordinates for the red points into an array.

This problem is by its very nature related to the incremental change of an angle. Your solution is going to need to deal with the angles using trig functions.

Post a Comment for "Calculate The X, Y Position Of A Canvas Point"