Search code examples
pythonmanim

How to draw STRAIGHT lines in manim?


I want to create a video with manim, which includes some straight lines.

Manim's class Line is actually line segments. Changing the buff attribute to an negative value doesn't work. I tried to calculate the intersect of the line with the screen border, but it's too complicated. Then I expand the line like this:

def expand_line(line: Line, ratio=100) -> None:
    ends = line.get_start_and_end()
    delta = ends[1] - ends[0]
    line.put_start_and_end_on(ends[0] - ratio * delta, ends[1] + ratio * delta)

It works well; but the animations like Create goes too fast.

Are there any classes or other better ways to draw straight lines?


Solution

  • I tried to calculate the intersect of the line with the screen border, but it's too complicated.

    You had the right idea here. Here's my solution:

    class Test(Scene):
        def extend_line(self, line: Sequence[np.ndarray], **kwargs):
            sr_points = ScreenRectangle(height=config.frame_height).get_vertices()
            inters = []
            for i in adjacent_pairs(sr_points):
                inters += [line_intersection(i, line)]
            inters.sort(key=np.linalg.norm)  # we want the nearest intersections
            return Line(*inters[:2], **kwargs)
    
        def construct(self):
            a = self.extend_line([LEFT * 2, UP])
            self.wait()
            self.play(Create(a))