PasteRack.org
Paste # 5630
2026-01-06 17:17:10

Fork as a new paste.

Paste viewed 73 times.


Embed:

string art by soegaard

  1. #lang racket
  2.  
  3. ;; Draw a "string art" figure like the one in the image:
  4. ;; Take N points on the curve (x(t), y(t)) = (sin t, sin(m t)),
  5. ;; then draw a chord from point i to point (i + k) mod N.
  6.  
  7. (require racket/gui/base)
  8.  
  9. (define WIDTH  1200)
  10. (define HEIGHT 900)
  11.  
  12. (define N  1200)  ;; number of sample points
  13. (define m  4)     ;; y frequency (controls the number of top/bottom bumps)
  14. (define k  137)   ;; chord step (choose relatively prime to N for a dense weave)
  15.  
  16. (define margin 40.0)
  17. (define sx (- (/ WIDTH  2.0) margin))
  18. (define sy (- (/ HEIGHT 2.0) margin))
  19. (define cx (/ WIDTH  2.0))
  20. (define cy (/ HEIGHT 2.0))
  21.  
  22. (define (pt i)
  23.   (define t (* 2.0 pi (/ i N)))
  24.   (define x (sin t))
  25.   (define y (sin (* m t)))
  26.   (values (+ cx (* sx x))
  27.           (+ cy (* sy y))))
  28.  
  29. (define bmp (make-bitmap WIDTH HEIGHT))
  30. (define dc  (new bitmap-dc% [bitmap bmp]))
  31.  
  32. ;; background
  33. (send dc set-brush (make-brush #:style 'solid #:color "black"))
  34. (send dc set-pen   (make-pen   #:style 'transparent))
  35. (send dc draw-rectangle 0 0 WIDTH HEIGHT)
  36.  
  37. ;; red, slightly transparent lines
  38. (send dc set-pen (make-pen #:width 1
  39.                            #:style 'solid
  40.                            #:cap 'round
  41.                            #:join 'round
  42.                            #:color (make-color 255 0 0 0.35)))
  43.  
  44. (for ([i (in-range N)])
  45.   (define j (modulo (+ i k) N))
  46.   (define-values (x1 y1) (pt i))
  47.   (define-values (x2 y2) (pt j))
  48.   (send dc draw-line x1 y1 x2 y2))
  49.  
  50. (send dc set-bitmap #f)
  51.  
  52. ;; Show it in a window
  53. (define frame
  54.   (new frame%
  55.        [label "String-art figure"]
  56.        [width WIDTH]
  57.        [height HEIGHT]))
  58.  
  59. (new canvas%
  60.      [parent frame]
  61.      [paint-callback
  62.       (λ (_ cdc)
  63.         (send cdc draw-bitmap bmp 0 0))])
  64.  
  65. (send frame show #t)
  66.  
  67. ;; Also save an image next to this program
  68. (send bmp save-file "string-art.png" 'png)

=>