Vectordrawing : Find a point in a path at mouse position

Share your advanced PureBasic knowledge/code with the community.
User avatar
[blendman]
Enthusiast
Enthusiast
Posts: 297
Joined: Thu Apr 07, 2011 1:14 pm
Location: 3 arks
Contact:

Vectordrawing : Find a point in a path at mouse position

Post by [blendman] »

Hi

I have search how to find a point on a path.
I think it could interest someone :)

So here is the code (based on the PathPointAngle() example ) :

Code: Select all


Structure sPoint
  x.w
  y.w
EndStructure
Global Dim CopyPathLength.SPoint(0)

Procedure EventCanvas(update=0)
  Static k
  
  If StartVectorDrawing(CanvasVectorOutput(0))
    
    If EventType() = #PB_EventType_LeftButtonDown Or (EventType() = #PB_EventType_MouseMove And GetGadgetAttribute(0, #PB_Canvas_Buttons) & #PB_Canvas_LeftButton)
      mx = GetGadgetAttribute(0, #PB_Canvas_MouseX)
      my = GetGadgetAttribute(0, #PB_Canvas_MouseY)
    EndIf
    
    a = 5
    MovePathCursor(150, 125)
    AddPathCurve(0, 270, 0, -150, 350, 180)
    
    ; Debug Str(PathCursorX())+"/"+Str(PathCursorY())

    For i=0 To ArraySize(CopyPathLength())
      x1 = CopyPathLength(i)\x
      y1 = CopyPathLength(i)\y
      If x1>=mx-a And x1<=mx+a  And y1>=my-a And y1<=my+a
        k = i
        update=1
        Break
      EndIf
    Next
    
    StopVectorDrawing()
  EndIf
  
  
  If update = 1
    If StartVectorDrawing(CanvasVectorOutput(0))
      
      AddPathBox(0,0,GadgetWidth(0),GadgetHeight(0))
      VectorSourceColor(RGBA(255,255,255,255))
      FillPath()
      
      MovePathCursor(150, 125)
      AddPathCurve(0, 270, 0, -150, 350, 180)
      
      x = PathPointX(k)
      y = PathPointY(k)
      a = PathPointAngle(k)
      
      VectorSourceColor($FF0000FF)
      StrokePath(5)
      
      AddPathCircle(x, y, 10)
      VectorSourceColor($FFFF0000)
      FillPath()
      
      MovePathCursor(x, y)
      AddPathLine(30*Cos(Radian(a)), 30*Sin(Radian(a)), #PB_Path_Relative)
      StrokePath(5)
      StopVectorDrawing()
    EndIf
  EndIf
  
EndProcedure

If OpenWindow(0, 0, 0, 400, 200, "PathPointX", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
  CanvasGadget(0, 0, 0, 400, 200)
  EventCanvas(1)
  
  ; precalculate the path and save it in an array
  If StartVectorDrawing(CanvasVectorOutput(0))
    MovePathCursor(150, 125)
    AddPathCurve(0, 270, 0, -150, 350, 180)
    n = PathLength()
    ReDim  CopyPathLength.SPoint(n)
    For i=0 To n
      CopyPathLength(i)\x = PathPointX(i) 
      CopyPathLength(i)\y = PathPointY(i)
    Next
    StopVectorDrawing()
  EndIf
  
  Repeat
    Event = WaitWindowEvent(1)
    If event=#PB_Event_Gadget
      If EventGadget() =0
        EventCanvas()
      EndIf
      
    EndIf
    
  Until Event = #PB_Event_CloseWindow
EndIf
Cheers :)