You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Manim的MathTex Mobject中插入内嵌自定义图形?

在Manim中用自定义图形替换MathTex公式的变量

实现思路

MathTex的每个字符/符号都是独立的子对象,你可以定位目标变量的位置,将自定义图形(包括VGroup组合的复合图形)匹配尺寸后移动到对应位置,或通过动画替换原变量。

分步实现代码

1. 基础框架与图形定义

from manim import *

class ReplaceMathVars(Scene):
    def construct(self):
        # 初始化公式
        formula = MathTex("x + y = z").scale(1.5)
        
        # 自定义复合图形1:带圆心点的蓝色圆
        circle_with_dot = VGroup(
            Circle(radius=0.4, color=BLUE, fill_opacity=0.3),
            Dot(color=BLUE).scale(1.5)
        )
        
        # 自定义复合图形2:带对角线的绿色正方形
        square_with_diag = VGroup(
            Square(side_length=0.6, color=GREEN, fill_opacity=0.2),
            Line(UP+LEFT, DOWN+RIGHT, color=GREEN).scale(0.4)
        )

2. 定位并替换变量

# 定位公式中的x变量
        var_x = formula.get_part_by_tex("x")
        # 缩放图形匹配变量高度,对齐基线
        circle_with_dot.scale_to_fit_height(var_x.get_height())
        circle_with_dot.align_to(var_x, DOWN)
        circle_with_dot.move_to(var_x)
        
        # 定位并替换y变量
        var_y = formula.get_part_by_tex("y")
        square_with_diag.scale_to_fit_height(var_y.get_height())
        square_with_diag.align_to(var_y, DOWN)
        square_with_diag.move_to(var_y)
        
        # 移除原变量(可选,若要完全替换而非覆盖)
        formula.remove(var_x, var_y)
        
        # 组合最终元素并添加到场景
        final_expr = VGroup(formula, circle_with_dot, square_with_diag)
        self.add(final_expr)

3. 动态替换动画

如果需要动画过渡效果,可使用ReplacementTransform或FadeTransform:

self.add(formula)
        self.wait(1)
        # 动画替换x为圆形组合
        self.play(ReplacementTransform(var_x, circle_with_dot))
        self.wait(1)
        # 动画替换y为方形组合
        self.play(FadeTransform(var_y, square_with_diag))
        self.wait(2)

关键注意点

  • 用scale_to_fit_height/scale_to_fit_width保证图形与原变量尺寸匹配,避免排版错位。
  • 复杂公式中,若get_part_by_tex定位失效,可直接通过子对象索引访问(如formula[0][2]对应第三个字符)。
  • 用align_to(var, DOWN)对齐图形与公式基线,确保视觉统一。

内容的提问来源于stack exchange,提问作者Cortado-J

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 14:22:28