Created
August 8, 2025 09:17
-
-
Save calpa/dec16701f05a7906b3bb34bfec888cc9 to your computer and use it in GitHub Desktop.
Pyodide demo: render Matplotlib chart in the browser with a fixed-top tag and centered modal overlay.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import matplotlib.pyplot as plt | |
import numpy as np | |
import io, base64, js | |
# 1) 產生圖表並轉成 data URL | |
x = np.linspace(0, 2*np.pi, 100) | |
y = np.sin(x) | |
plt.figure(figsize=(6, 4), dpi=120) | |
plt.plot(x, y, '--', linewidth=2) | |
plt.title('Sine in the Browser') | |
plt.tight_layout() | |
buf = io.BytesIO() | |
plt.savefig(buf, format="png", bbox_inches="tight", facecolor="white") | |
buf.seek(0) | |
data_url = "data:image/png;base64," + base64.b64encode(buf.read()).decode("ascii") | |
plt.close() | |
# 2) 頂端置中標籤 | |
tag = js.document.createElement("div") | |
tag.textContent = "Pyodide × Matplotlib" | |
tag.style.cssText = ( | |
"position:absolute;top:0;left:50%;transform:translateX(-50%);z-index:10000;" | |
"background:rgba(0,0,0,.7);color:#fff;padding:6px 10px;border-radius:0 0 8px 8px;" | |
) | |
js.document.body.append(tag) | |
# 3) 灰色半透明遮罩 + 置中容器(無事件) | |
overlay = js.document.createElement("div") | |
overlay.style.cssText = ( | |
"position:fixed;inset:0;background:rgba(0,0,0,.5);display:flex;" | |
"align-items:center;justify-content:center;z-index:9999;" | |
) | |
modal = js.document.createElement("div") | |
modal.style.cssText = ( | |
"background:#f5f5f5;padding:16px;border-radius:12px;" | |
"box-shadow:0 10px 30px rgba(0,0,0,.2);max-width:95vw;max-height:80vh;" | |
) | |
img = js.document.createElement("img") | |
img.style.cssText = "max-width:90vw;max-height:70vh;display:block;" | |
img.src = data_url | |
img.alt = "Matplotlib Sine" | |
# 4) 組裝 | |
modal.append(img) | |
overlay.append(modal) | |
js.document.body.append(overlay) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment