Introduction Lines Circles Sharp Waves Curly Waves Colors Lines Between Two Points Arcs Between Two Points

Lines between Two Points - Maths317

First the distance between the Two Points

Given the Points A \((x_0, y_0)\) and B \((x_1, y_1)\) , the distance formula is : \( D = \sqrt{ (x_1 - x_0)^2 + (y_1 - y_0)^2 } \)

Second the angle between the Two points

Using algebra with our line formula found in Lines for point x, we calculate the angle to be \( \theta = cos^{-1} { (x_1 - x_0) \over D } \)

After find this two values we can then use the method presented in Lines for calculating the points for drawing

Test Code


package main

import (
  "github.com/disintegration/imaging"
  "image/color"
  "math"
  "math/rand"
  "time"
  "fmt"
)

func main() {
  img := imaging.New(500, 300, color.White)

  src := rand.NewSource(time.Now().UnixNano())
  seededRand := rand.New(src)

  x0 := seededRand.Intn(50)
  y0 := seededRand.Intn(50)

  x1 := seededRand.Intn(200)
  y1 := seededRand.Intn(200)

  fmt.Printf("A(%d, %d)\n", x0, y0)
  fmt.Printf("B(%d, %d)\n", x1, y1)

  diffX := x1 - x0
  diffY := y1 - y0
  tmp2 := math.Pow(float64(diffX), 2)
  tmp3 := math.Pow(float64(diffY), 2)
  distanceFromAtoBFloat := math.Sqrt(tmp2 + tmp3)
  distanceFromAtoB := int(math.Round(distanceFromAtoBFloat))

  fmt.Println("length is ", distanceFromAtoB)

  angleInRadians := math.Acos( float64(diffX)/ distanceFromAtoBFloat)

  angleFloat := angleInRadians * 180 / math.Pi
  fmt.Println("angle is %.4f", angleFloat)

  storedX := float64(x0)
  storedY := float64(y0)

  for i := 1; i < distanceFromAtoB; i++ {
    storedX = storedX + math.Cos(angleInRadians)
    storedY = storedY + math.Sin(angleInRadians)

    img.Set(int(math.Round(storedX)), int(math.Round(storedY)), color.Black)
  }

  err := imaging.Save(img, "out_line2.png")
  if err != nil {
    panic(err)
  }
}

Note that the math functions in golang expects the angles in radians which was converted with the formula:

\(R = \theta {pi \over 180} \)

References

  1. Ref 1
< Previous Next >