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(layout="wide")
# Initialize canvas state
if 'drawing_points' not in st.session_state:
st.session_state.drawing_points = []
if 'drawing' not in st.session_state:
st.session_state.drawing = False
# Create a white canvas with grid
def create_grid_canvas(width=800, height=600):
# Create a white background
img = Image.new('RGB', (width, height), 'white')
draw = ImageDraw.Draw(img)
# Draw grid lines
grid_spacing = 20
# Vertical lines
for x in range(0, width, grid_spacing):
draw.line([(x, 0), (x, height)], fill='#e0e0e0', width=1)
# Horizontal lines
for y in range(0, height, grid_spacing):
draw.line([(0, y), (width, y)], fill='#e0e0e0', width=1)
return img
# Create canvas
canvas_width = 800
canvas_height = 600
canvas = create_grid_canvas(canvas_width, canvas_height)
draw = ImageDraw.Draw(canvas)
# Handle mouse events
def on_mouse_down(event):
st.session_state.drawing = True
st.session_state.drawing_points.append((event.offsetX, event.offsetY))
def on_mouse_move(event):
if st.session_state.drawing:
st.session_state.drawing_points.append((event.offsetX, event.offsetY))
# Draw the line
if len(st.session_state.drawing_points) > 1:
draw.line([st.session_state.drawing_points[-2], st.session_state.drawing_points[-1]],
fill='black', width=2)
st.rerun()
def on_mouse_up(event):
st.session_state.drawing = False
# Create the canvas element
canvas_container = st.empty()
canvas_container.image(canvas, use_column_width=True)
# Add mouse event listeners using HTML/JavaScript
st.markdown("""
<canvas id="drawingCanvas" style="border:1px solid #000000;"></canvas>
<script>
const canvas = document.getElementById('drawingCanvas');
canvas.width = 800;
canvas.height = 600;
const ctx = canvas.getContext('2d');
let isDrawing = false;
let lastX = 0;
let lastY = 0;
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('mouseout', stopDrawing);
function startDrawing(e) {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
}
function draw(e) {
if (!isDrawing) return;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
[lastX, lastY] = [e.offsetX, e.offsetY];
}
function stopDrawing() {
isDrawing = false;
}
</script>
""", unsafe_allow_html=True)
# Clear button
if st.button("Clear Canvas"):
st.session_state.drawing_points = []
canvas = create_grid_canvas(canvas_width, canvas_height)
canvas_container.image(canvas, use_column_width=True)
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?