iamseeley-pyodidepowersvis.web.val.run
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
export const pyodideExample = () => {
const html = `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Pyodide App</title>
<script type="text/javascript" src="https://cdn.jsdelivr.net/pyodide/v0.25.1/full/pyodide.js"></script>
</head>
<body>
<h1>Calculate the square of a number and visualize powers using Python in WebAssembly</h1>
<input type="number" id="number" placeholder="Enter a number">
<button id="calculate">Calculate</button>
<p id="result"></p>
<div id="plot"></div>
<script>
async function main() {
let pyodide = await loadPyodide();
await pyodide.loadPackage('matplotlib');
console.log('Pyodide is ready to use!');
pyodide.runPython(\`
import matplotlib.pyplot as plt
import io
import base64
def square(x):
return x * x
def plot_powers(n):
x = list(range(1, n+1))
y_square = [i**2 for i in x]
y_cube = [i**3 for i in x]
plt.figure()
plt.plot(x, y_square, label='Square')
plt.plot(x, y_cube, label='Cube')
plt.xlabel('Number')
plt.ylabel('Value')
plt.title('Powers of Numbers')
plt.legend()
plt.grid(True)
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
img = base64.b64encode(buf.read()).decode('utf-8')
return img
\`);
return pyodide;
}
const pyodide = main();
const calculateButton = document.getElementById('calculate');
const numberInput = document.getElementById('number');
const resultElement = document.getElementById('result');
const plotContainer = document.getElementById('plot');
calculateButton.addEventListener('click', async () => {
const number = parseInt(numberInput.value);
const result = await pyodide.then(pyodide => pyodide.runPython(\`square(\${number})\`));
resultElement.textContent = \`The square of \${number} is \${result}.\`;
const img = await pyodide.then(pyodide => pyodide.runPython(\`plot_powers(\${number})\`));
plotContainer.innerHTML = \`<img src="data:image/png;base64,\${img}" />\`;
});
</script>
</body>
</html>
`;
return new Response(html, {
headers: {
"Content-Type": "text/html",
},
});
};
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
May 18, 2024