manim

Combining Tex and MObject in Manim


Is there a way to combine MObjects and Tex Objects in one place with the same height/font size? I tried VGroup and setting manually the width, but that doesn't work due to different shapes of single letter (bounding box)

Specifically, I am trying to do something like the attached image:

enter image description here

or this one:

enter image description here

The full video where I got these screenshots can be found here: https://www.youtube.com/watch?v=KuXjwB4LzSA


Solution

  • I don't think it's possible to directly combine MObjects and Tex Objects. However, you could use a height from one of the letters/symbols you already have and use that. In the second example, the plus sign seems to have the same size as the rectangles so lets use that:

    from manim import *
    
    
    class Test(Scene):
        def construct(self):
            text = MathTex("P(", "xx", "+", "xx", "=6 ) = {5 \\over 36} ", font_size=64)
            height = text[2].height
            red_rect = Rectangle(
                height=height,
                width=height,
                fill_color=RED,
                fill_opacity=1.0,
                stroke_width=1,
            ).move_to(text[1].get_center())
            blue_rect = red_rect.copy().set(fill_color=BLUE).move_to(text[3].get_center())
    
            self.add(text[0], text[2], text[4], red_rect, blue_rect)
    
            self.wait(3)
    
    

    Here is the result:

    result

    I used the "xx" strings as a placeholder, but there are multiple other ways to arrange the text and objects. The rectangles look a bit different, I have to assume, but this was not the key point of the question, so I hope that's fine.