8000 jschart not working · Issue #2354 · pyscript/pyscript · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
jschart not working #2354
Open
Open
@quantrpeter

Description

@quantrpeter

Checklist

  • I added a descriptive title
  • I searched for other issues and couldn't find a solution or duplication
  • I already searched in Google and didn't find any good information or help

What happened?

chartjs not working

def main():
    print("Initializing PyScript application...")
    # Hide loading indicator
    from js import document
    loading = document.getElementById("loading")
    if loading:
        loading.style.display = "none"
    # Draw chart after loading
    draw_chart()
    # Here you can call functions from utils.py as needed
    # For example: result = utils.some_function()

from js import document, fetch, window
from pyodide.ffi import create_proxy, to_js
import asyncio
from js import console, Chart, Object

def draw_chart():
    console.log("Drawing chart...")
    ctx = document.getElementById("myChart")
    if ctx:
        console.log("Canvas element found!")
    else:
        console.log("Canvas element not found!")
        return
    if hasattr(window, "Chart"):
        console.log("Chart.js is available!")
    else:
        console.log("Chart.js is not available!")
        return
    try:
        chart_config = {
            "type": "bar",
            "data": {
                "labels": ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
                "datasets": [{
                    "label": "Number of Votes",
                    "data": [12, 19, 3, 5, 2, 3],
                    "backgroundColor": [
                        "rgba(255, 99, 132, 0.2)",
                        "rgba(54, 162, 235, 0.2)",
                        "rgba(255, 206, 86, 0.2)",
                        "rgba(75, 192, 192, 0.2)",
                        "rgba(153, 102, 255, 0.2)",
                        "rgba(255, 159, 64, 0.2)"
                    ],
                    "borderColor": [
                        "rgba(255, 99, 132, 1)",
                        "rgba(54, 162, 235, 1)",
                        "rgba(255, 206, 86, 1)",
                        "rgba(75, 192, 192, 1)",
                        "rgba(153, 102, 255, 1)",
                        "rgba(255, 159, 64, 1)"
                    ],
                    "borderWidth": 1
                }]
            },
            "options": {
                "scales": {
                    "y": {
                        "beginAtZero": True
                    }
                },
                "responsive": False,  # Explicitly disable responsive to match canvas size
                "animation": False   # Disable animation to ensure immediate render
            }
        }
        # Create chart with explicit object conversion
        chart = Chart.new(ctx, to_js(chart_config, dict_converter=window.Object.new))
        console.log("Chart initialized successfully!")
        # Force chart update
        chart.update()
        console.log("Chart update called!")
    except Exception as e:
        console.log(f"Error initializing chart: {str(e)}")

if __name__ == "__main__":
    main()

change to eval then it work

def main():
    print("Initializing PyScript application...")
    # Hide loading indicator
    from js import document
    loading = document.getElementById("loading")
    if loading:
        loading.style.display = "none"
    # Draw chart after loading
    draw_chart()

from js import document, fetch, window
from pyodide.ffi import create_proxy, to_js
import asyncio
from js import console, Chart, Object

def draw_chart():
    console.log("Drawing chart...")
    ctx = document.getElementById("myChart")
    if ctx:
        console.log("Canvas element found!")
    else:
        console.log("Canvas element not found!")
        return
    if hasattr(window, "Chart"):
        console.log("Chart.js is available!")
    else:
        console.log("Chart.js is not available!")
        return
    try:
        # Use JavaScript to create the chart
        js_code = """
            const ctx = document.getElementById('myChart');
            new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
                    datasets: [{
                        label: 'Number of Votes',
                        data: [12, 19, 3, 5, 2, 3],
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.2)',
                            'rgba(54, 162, 235, 0.2)',
                            'rgba(255, 206, 86, 0.2)',
                            'rgba(75, 192, 192, 0.2)',
                            'rgba(153, 102, 255, 0.2)',
                            'rgba(255, 159, 64, 0.2)'
                        ],
                        borderColor: [
                            'rgba(255, 99, 132, 1)',
                            'rgba(54, 162, 235, 1)',
                            'rgba(255, 206, 86, 1)',
                            'rgba(75, 192, 192, 1)',
                            'rgba(153, 102, 255, 1)',
                            'rgba(255, 159, 64, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    },
                    responsive: false,
                    animation: false
                }
            });
        """
        window.eval(js_code)
        console.log("Chart initialized via JavaScript!")
    except Exception as e:
        console.log(f"Error initializing chart: {str(e)}")

if __name__ == "__main__":
    main()

testing HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PyScript Project</title>
    <!-- <script defer src="https://pyscript.net/latest/pyscript.js"></script> -->
    <script type="module" src="https://pyscript.net/releases/2024.5.2/core.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script type="py" src="src/main.py"></script>
    <style>
        .blue-border {
            border: 2px solid blue !important;
        }
        #loading {
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            background: white;
            z-index: 9999;
            font-size: 2em;
        }
    </style>
</head>
<body>
    <div id="loading">Loading PyScript...</div>
    <h1>Welcome to the PyScript Project</h1>
    <div id="versionDiv"></div>
    <canvas id="myChart" width="1400" height="1200"></canvas>

</body>
</html>

What browsers are you seeing the problem on? (if applicable)

No response

Console info

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0