I made this dash-svm-2022 app. And this is a 2022 copy of the one of official demo. I’ve tried those new features, those new components. Amazing! The experience is so much better than when I was new to dash. Thank you Plotly for your efforts over the past few years.
And could someone teach me how to write a nice client-side callback? I want to add grids and axes to the canvas, as well as a ‘one-click clear’ button. And I have to figure out a way to prevent the user from drawing lines. Please help me, thanks a lot!
Ah, this is my MRE.
from dash import Dash, html, dcc, dash_table, Input, Output, State, no_update, get_asset_url
from dash.exceptions import PreventUpdate
from dash_canvas import DashCanvas
import pandas as pd
import json
app = Dash(__name__)
canvas_width = 800
columns = ['stroke', 'path', 'pathOffset']
app.layout = html.Div(
[
html.H6('---------------------------------'),
DashCanvas(
id='annot-canvas',
#filename=get_asset_url('canvas_bg.png'),
lineWidth=5,
goButtonTitle='Generate',
lineColor='#509188',
hide_buttons=[
"zoom", "pan", "line", "pencil", "rectangle", "select"
]),
btn := html.Button('Toggle'),
btn2 := html.Button('Clear'),
btn3 := html.Button('Grids'),
dash_table.DataTable(id='canvas-table',
style_cell={'textAlign': 'left'},
columns=[{
"name": i,
"id": i
} for i in columns]),
div := html.Div(),
],
style={'height': '1000px'})
@app.callback(Output('canvas-table', 'data'), Input('annot-canvas',
'json_data'))
def update_data(string):
if string:
df = pd.DataFrame(json.loads(string)['objects'])
else:
raise PreventUpdate
dff = df[columns]
dff['path'] = dff['path'].apply(lambda x: str(x))
dff['pathOffset'] = dff['pathOffset'].apply(lambda x: str(x))
return dff.to_dict('records')
@app.callback(Output(div, 'children'), Input('annot-canvas', 'json_data'))
def showme(string):
return string
app.clientside_callback(
"""
function(n, c) {
if (c === '#509188') {
return '#FF7070'
} else {
return '#509188'
}
}
""", Output('annot-canvas', 'lineColor'), [Input(btn, 'n_clicks')],
[State('annot-canvas', 'lineColor')])
if __name__ == '__main__':
app.run_server(debug=True)