diff --git a/CrossDown/Core.py b/CrossDown/Core.py index a532a9c..1a401b9 100644 --- a/CrossDown/Core.py +++ b/CrossDown/Core.py @@ -31,9 +31,8 @@ Extensions = { } try: # 检测当前平台是否支持扩展语法 - import Extra - - Extensions += Extra.EXTRA + from .Extra import * + EXTRA_ABLE = True except ModuleNotFoundError: EXTRA_ABLE = False @@ -206,9 +205,20 @@ class CodeLine(Treeprocessor): elem.remove(code) elif re.match(r'¥[^$]*¥', code.text): # 是数学函数(单行) if EXTRA_ABLE: - expression, range_ = re.findall(r'¥([^$]*)¥(€[^$]*€)?', code)[0] # 分离表达式与范围(如果有) + expression, range_ = re.findall(r'¥([^$]*)¥(€[^$]*€)?', code.text)[0] # 分离表达式与范围(如果有) x_r = (-10, 10) y_r = (-20, 20) + if range_ != '': # 定义了范围 + ranges = range_[1:-1].split('|') + if len(ranges) in (1, 2): # 定义的范围正确 + x_r = tuple(int(i) for i in ranges[0].split(',')) + if len(ranges) == 2: # 定义了y范围 + y_r = tuple(int(i) for i in ranges[1].split(',')) + code.tag = 'img' + code.set('src', f"""data:image/png;base64,{(function_drawing( + function=lambda x: eval(expression.split('=')[1]), x_range=x_r, y_range=y_r + ))}""") # 绘制函数图像 + code.set('alt', 'Base64 函数图片') elif re.match(r'\{[^$]*}', code.text): # 是强调 code.tag = 'span' code.set('class', 'block') diff --git a/CrossDown/Extra.py b/CrossDown/Extra.py index 45f343c..40efbb1 100644 --- a/CrossDown/Extra.py +++ b/CrossDown/Extra.py @@ -1,3 +1,43 @@ +import matplotlib.pyplot as plt +import numpy as np +import base64 +from io import BytesIO + + EXTRA = [ ] + + +def function_drawing(function, x_range=(-10, 10), y_range=(-20, 20), dpi=100): + # 创建一个图像和坐标轴对象 + fig, ax = plt.subplots() + + # 生成x值 + x = np.linspace(x_range[0], x_range[1], 400) + + # 计算y值 + y = function(x) + + # 绘制图像 + ax.plot(x, y) + + # 设置坐标轴范围 + ax.set_xlim(x_range) + ax.set_ylim(y_range) + + # 隐藏坐标轴 + ax.axis('on') + + # 将图像保存到BytesIO对象 + buf = BytesIO() + fig.savefig(buf, format='png', dpi=dpi) + + # 获取图像数据的Base64编码 + data = base64.b64encode(buf.getbuffer()).decode("ascii") + + # 关闭图像和坐标轴对象 + plt.close(fig) + + # 返回Base64编码的字符串 + return data diff --git a/README.html b/README.html index f284751..5e80a9e 100644 --- a/README.html +++ b/README.html @@ -175,9 +175,9 @@
这是\(CO_2\)二氧化碳
这是\(H_2O\)水
¥y=x*2+1¥
// 不定义范围
¥y=x**2¥€-50,50€
// 定义了x范围
¥y=x**3¥€-50,50|-100,100€
// 定义了y范围
// 不定义范围
+// 定义了x范围
+// 定义了y范围
强调文本