-
Notifications
You must be signed in to change notification settings - Fork 2
/
canvas-animation-circle.html
57 lines (57 loc) · 2.1 KB
/
canvas-animation-circle.html
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
<!DOCTYPE html><html><head>
<!--code at: https://github.com/ostad-ai/Miscellaneous-->
<script defer src="https://pyscript.net/alpha/pyscript.min.js"></script>
<style>button{font-size:20px;}</style></head><body>
<h1 style="color:#00a2fa;">Python inside HTML: Animating circles</h1>
<h3>Code by <i>Hamed Shah-Hosseini</i>, at: https://github.com/ostad-ai/Miscellaneous </h3>
<button id="mybuttonstart" pys-onClick="start">Start animation</button>
<button id="mybuttonstop" pys-onClick="stop">Stop animation</button>
<canvas id="my-canvas"></canvas></div><py-script>
from js import window, setInterval,clearInterval
from pyodide import create_proxy
import random; from math import pi
canvas=Element("my-canvas").element;
canvas.width=window.innerWidth-12; canvas.height=500
ctx = canvas.getContext("2d")
ret=None
def start(*args,**kwargs):
global ret
if ret==None:
ret=setInterval(create_proxy(run),30)
def stop(*args,**kwargs):
global ret
clearInterval(ret)
ret=None
class Circle:
def __init__(self,x,y,radius):
self.x=x; self.y=y
self.radius=radius+random.randint(0,30)
r,g,b=random.randint(0,200),random.randint(0,200),random.randint(0,200)
self.color=f'rgba({r},{g},{b},.8)'
self.width=canvas.width
self.height=canvas.height
self.dx=2+random.randint(0,20)
self.dy=3+random.randint(0,20)
def draw(self):
ctx.beginPath()
ctx.fillStyle=self.color
ctx.arc(self.x, self.y, self.radius, 0, 2 * pi)
ctx.fill()
if (self.x>=(self.width-self.radius)) or (self.x < self.radius):
self.dx=-self.dx
if (self.y>=(self.height-self.radius)) or (self.y < self.radius):
self.dy=-self.dy
self.x+=self.dx; self.y+=self.dy
circles=[]
for i in range(30):
circles.append(Circle(canvas.width//2,canvas.height//2,20))
def run():
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.beginPath()
ctx.lineWidth='5'
ctx.strokeStyle='yellow'
ctx.rect(0,0,canvas.width,canvas.height)
ctx.stroke()
for circle in circles:
circle.draw()
</py-script></body></html>