Replicate the app from the image.
To upload files, please first save the app
import streamlit as st
import numpy as np
from PIL import Image, ImageDraw
# Set page config
st.set_page_config(page_title="Drawing Canvas")
# Initialize canvas
canvas_width = 800
canvas_height = 600
grid_size = 20
# Create a new image with a white background and grid
def create_grid_image():
# Create a white background
image = Image.new('RGB', (canvas_width, canvas_height), 'white')
draw = ImageDraw.Draw(image)
# Draw vertical grid lines
for x in range(0, canvas_width, grid_size):
draw.line([(x, 0), (x, canvas_height)], fill='lightgray', width=1)
# Draw horizontal grid lines
for y in range(0, canvas_height, grid_size):
draw.line([(0, y), (canvas_width, y)], fill='lightgray', width=1)
return image
# Initialize session state for storing drawing data
if 'drawing_points' not in st.session_state:
st.session_state.drawing_points = []
# Create canvas container
canvas_container = st.empty()
# Display initial grid
if not st.session_state.drawing_points:
canvas_container.image(create_grid_image())
# Handle mouse events
def handle_click():
# Get mouse coordinates (Note: This is a simplified version, actual mouse handling
# would require JavaScript components which aren't available in basic Streamlit)
x = st.slider("X coordinate", 0, canvas_width, 400)
y = st.slider("Y coordinate", 0, canvas_height, 300)
if st.button("Add Point"):
st.session_state.drawing_points.append((x, y))
update_canvas()
def update_canvas():
img = create_grid_image()
draw = ImageDraw.Draw(img)
# Draw lines between points
points = st.session_state.drawing_points
if len(points) > 1:
draw.line(points, fill='black', width=2)
canvas_container.image(img)
# Add controls
st.sidebar.title("Drawing Controls")
handle_click()
# Add clear button
if st.sidebar.button("Clear Canvas"):
st.session_state.drawing_points = []
canvas_container.image(create_grid_image())
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?