這是一個經過修補的 streamlit-drawable-canvas 版本,專門為解決 Streamlit 1.44.0+ 的不相容問題而設計。
原始套件 (streamlit-drawable-canvas==0.9.3) 使用了 Streamlit 已廢棄的內端 API image_to_url,這會導致:
- AttributeError:
module 'streamlit.elements.image' has no attribute 'image_to_url' - 背景圖片 404: 即便繞過報錯,背景圖片也無法正常載入。
- 核心修復: 移除了對 Streamlit 內部
image_to_url的依賴。 - 背景圖片支援: 使用 Base64 編碼傳輸背景圖片,解決了 404 載入問題。
- 重新掛載機制: 加入了動態 Key 技術,當背景圖片更換時,畫布會強制更新並重新渲染背景(解決 Fabric.js 背景不刷新的問題)。
目前您可以直接將 streamlit_drawable_canvas 資料夾複製到您的專案中,或者:
# 後續將支援 pip 安裝
pip install streamlit-drawable-canvas-fixedfrom streamlit_drawable_canvas import st_canvas
import streamlit as st
from PIL import Image
bg_image = Image.open("background.png")
canvas_result = st_canvas(
fill_color="rgba(255, 165, 0, 0.3)",
stroke_width=3,
stroke_color="#000",
background_image=bg_image,
update_streamlit=True,
height=400,
width=600,
drawing_mode="freedraw",
key="canvas",
)基於原始專案的 MIT License。