From eea7b91618c551c73bf72575d728780987048a29 Mon Sep 17 00:00:00 2001 From: "Yuichiro Tachibana (Tsuchiya)" Date: Tue, 6 Jun 2023 01:29:02 +0900 Subject: [PATCH] Fix a logic to get the base URL of a background image (#117) --- streamlit_drawable_canvas/__init__.py | 5 ++--- .../frontend/src/DrawableCanvas.tsx | 19 ++++++++++++++++--- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/streamlit_drawable_canvas/__init__.py b/streamlit_drawable_canvas/__init__.py index fcf0436..f7f0554 100644 --- a/streamlit_drawable_canvas/__init__.py +++ b/streamlit_drawable_canvas/__init__.py @@ -5,6 +5,7 @@ from hashlib import md5 import numpy as np +import streamlit as st import streamlit.components.v1 as components import streamlit.elements.image as st_image from PIL import Image @@ -124,9 +125,7 @@ def st_canvas( background_image_url = st_image.image_to_url( background_image, width, True, "RGB", "PNG", f"drawable-canvas-bg-{md5(background_image.tobytes()).hexdigest()}-{key}" ) - # always send relative URLs, the frontend handles this - if background_image_url[0] == '/': - background_image_url = background_image_url[1:] + background_image_url = st._config.get_option("server.baseUrlPath") + background_image_url background_color = "" # Clean initial drawing, override its background color diff --git a/streamlit_drawable_canvas/frontend/src/DrawableCanvas.tsx b/streamlit_drawable_canvas/frontend/src/DrawableCanvas.tsx index 43ead1e..ad70899 100644 --- a/streamlit_drawable_canvas/frontend/src/DrawableCanvas.tsx +++ b/streamlit_drawable_canvas/frontend/src/DrawableCanvas.tsx @@ -13,6 +13,20 @@ import UpdateStreamlit from "./components/UpdateStreamlit" import { useCanvasState } from "./DrawableCanvasState" import { tools, FabricTool } from "./lib" +function getStreamlitBaseUrl(): string | null { + const params = new URLSearchParams(window.location.search) + const baseUrl = params.get("streamlitUrl") + if (baseUrl == null) { + return null + } + + try { + return new URL(baseUrl).origin + } catch { + return null + } +} + /** * Arguments Streamlit receives from the Python side */ @@ -113,9 +127,8 @@ const DrawableCanvas = ({ args }: ComponentProps) => { bgImage.onload = function() { backgroundCanvas.getContext().drawImage(bgImage, 0, 0); }; - const params = new URLSearchParams(window.location.search); - const baseUrl = params.get('streamlitUrl') - bgImage.src = baseUrl + backgroundImageURL; + const baseUrl = getStreamlitBaseUrl() ?? "" + bgImage.src = baseUrl + backgroundImageURL } }, [ canvas,