def main(i): def animate(i): global id id = raf(animate) draw() def draw(): Game.context.clearRect(0, 0, Game.canvas.width, Game.canvas.height) lvl.draw() Mob.update('Puce') player.update() Mob.draw('Puce') player.draw() global p p.style = {'display': "none"} Game.canvas = html.CANVAS(width=SET.WINDOW_SIZE[0], height=SET.WINDOW_SIZE[1]) mL = (doc.body.clientWidth - SET.WINDOW_SIZE[0]) / 2 Game.canvas.style = {"border": "1px solid black", 'marginLeft': "{}px".format(mL)} Game.context = Game.canvas.getContext("2d") if not Game.canvas: alert("Can't access to the canvas") Game.context = Game.canvas.getContext('2d') if not Game.context: alert("Can't access to the canvas") lvl = Level() player = Player(lvl) doc.body.addEventListener("keydown", player.player_event) doc.body.addEventListener("keyup", player.player_event) animate(0) doc.body.append(Game.canvas)
def __init__(self, width, height, title="", fps=60): self.width = width self.height = height self.title = title self.done = False self.fps = fps self.listeners = [] self.draw_func = None self.init_func = None self.keys = dict([(a, False) for a in range(255)] + [(a, False) for a in range(0xff00, 0xffff)]) c = html.CANVAS(width=self.width, height=self.height, id="canvas") doc <= c self.canvas = doc["canvas"] self.ctx = self.canvas.getContext('2d') doc <= html.TITLE(self.title) doc.bind("keydown", self._keydown) doc.bind("keyup", self._keyup) #doc.bind('load', self.pageshow) self.soundPlayers = {}
def size(self, text): _canvas = html.CANVAS(width=1000, height=1000) _ctx = _canvas.getContext('2d') #_ctx.fillText(text, 0, 0) # get text metrics _metrics = _ctx.measureText(text) return (_metrics.width, _metrics.height)
def __init__(self, dim, depth=16): self._width = dim[0] self._height = dim[1] self._depth = depth self._canvas = html.CANVAS(width=self._width, height=self._height) self._context = self._canvas.getContext('2d') document['py_div'] <= self._canvas
def copy(self): _imgdata=self._context.toDataURL('image/png') _canvas=html.CANVAS(width=self._canvas.width,height=self._canvas.height) _ctx=_canvas.getContext('2d') _ctx.drawImage(_imgdata, 0, 0) return _canvas
def init(): global SCREEN, CTX document.body.append(html.H1("Browser Invaders - a Python adventure")) SCREEN = html.CANVAS(width=WIDTH, height=HEIGHT) SCREEN.style = {"background": "black"} document.body.append(SCREEN) CTX = SCREEN.getContext("2d") for image_name in "ship", "enemy_01", "enemy_02": images[image_name] = html.IMG(src="images/{}.png".format(image_name)) print("loaded {}.png".format(image_name))
def render(self, text, antialias, color, background=None): _canvas = html.CANVAS() _ctx = _canvas.getContext('2d') if background is not None: _ctx.fillStyle = 'rgb(%s,%s,%s)' % color _ctx.fillRect(0, 0, _canvas.width, _canvas.height) _ctx.fillStyle = 'rgb(%s,%s,%s)' % color _ctx.fillText(text, 0, 0) return surface.Surface(surf=_canvas) #surface
def __init__(self): super().__init__(style=dict(left=0, top=0, width=900, height="600px")) canvas = html.CANVAS() canvas.id = "CursorLayer" canvas.width = 800 canvas.height = 600 #canvas.style.zIndex = 8; canvas.style.position = "absolute" canvas.style.border = "1px solid" self.elt <= canvas self.ctx = canvas.getContext('2d') self.pix = self.ctx.createImageData(1, 1) self.pixd = self.pix.data
def __init__(self, dim=[], depth=16, surf=None): global canvas_ID if surf is None: self._depth=depth self._canvas=html.CANVAS(width=dim[0], height=dim[1]) elif isinstance(surf, Surface): self._canvas=surf.copy() elif isinstance(surf, html.CANVAS): self._canvas=surf self._context=self._canvas.getContext('2d') self._canvas.id='layer_%s' % canvas_ID canvas_ID += 1
def __init__(self, id, parentID=None): self._id = id if parentID is not None: _parent = document[parentID] _canvas = html.CANVAS(id='canvas', style={ 'width': _parent.width, 'height': _parent.height, 'background-color': 'black' }) _parent <= _canvas self._canvas = document[id]
def __init__(self, cena, tit=""): self.color = "blue" canvas = html.CANVAS(width=CNV, height=200) cena.html = "" cena <= canvas self.prt = html.DIV() self.prt.html = "" cena <= self.prt self.ctx = canvas.getContext("2d") self.tit = tit self.dataset = [] self.figure_title() self.axis()
def init(): global canvas, overlay, map, mpos #ele = doc["map"] #if not ele.getContext: # alert('An error occured creating a Canvas 2D context. ' # 'This may be because you are using an old browser') # return #map=ele.getContext("2d") _css = doc.createElement('link') _css.type = "text/css" _css.rel = "stylesheet" _css.href = "gallery/brython/css/3Dwalker.css" doc['pydiv'] <= _css _app = html.DIV(id="app") _app <= html.CANVAS(id="underMap", width="80px", height="80px") _app <= html.CANVAS(id="map", width="80px", height="80px") doc['pydiv'] <= html.DIV(id="content") doc['content'] <= _app _app <= html.DIV(id='holder') doc['holder'] <= html.DIV(id='sky') doc['holder'] <= html.DIV(id='floor') doc['holder'] <= html.CANVAS(id='canvas', width="400px", height="300px") doc['holder'] <= html.DIV(id='overlay') canvas = doc["canvas"].getContext("2d") overlay = doc["overlay"] map = doc["map"].getContext('2d') doc["sky"].style.backgroundPosition = "%spx 0" % floor(-playerDir / (2 * pi) * 2400) drawCanvas() initUnderMap() timer.set_interval(update, 35)
def __init__(self, dim=[], depth=16, surf=None): if surf is None: self._depth = depth self._canvas = html.CANVAS(width=dim[0], height=dim[1]) elif isinstance(surf, Surface): self._canvas = surf.copy() #self._width=surf.get_width() #self._height=surf.get_height() elif isinstance(surf, html.CANVAS): self._canvas = surf #self._width=surf.style.width #self._height=surf.style.height self._context = self._canvas.getContext('2d') self._canvas.id = 'layer_%s' % random.randint(0, 99999999)
def createCanvas(w, h): global _canvas, _ctx, width, height _body = document.select("body")[0] _canvas = html.CANVAS(width=w, height=h) _canvas.width = w _canvas.height = h _body <= _canvas _ctx = _canvas.getContext("2d") _canvas.bind("mousedown", _mousedown) _canvas.bind("mousemove", _mousemove) _canvas.bind("mouseup", _mouseup) stroke("black") fill("white") width = w height = h
def __init__(self, network): self.dx = network.dt self.net = network self.canvas = html.CANVAS(id='canv', width=1000, height=1000) self.container = html.DIV() self.container <= self.canvas self.inputs = {} self.params = { "dt": self.net.dt, "dxdt": "2 - x", "n_nodes": len(self.net.nodes), "network": "fixedlattice" } document <= self.container self._destroy_frame_interval = 100 self._ticks = 0
def init(): global SCREEN, CTX document.body.append(html.H1("Browser Invaders - a Python adventure") ) #display program title to user SCREEN = html.CANVAS( width=WIDTH, height=HEIGHT) #create game screen with set hight and width SCREEN.style = { "background": "black" } #set the screen's background to black document.body.append(SCREEN) CTX = SCREEN.getContext("2d") #load images for the ship and both enemies, #and print an acknowledgement after each load for image_name in "ship", "enemy_01", "enemy_02": images[image_name] = html.IMG(src="images/{}.png".format(image_name)) print("loaded {}.png".format(image_name))
def load_basic(file, namehint=''): '''Load BMP image from a file. :see: `load` :Parameters: `file` : str or file-like object Image file or filename to load. `namehint` : str Ignored, for compatibility. :rtype: `Surface` ''' #if not hasattr(file, 'read'): # surf = SDL_LoadBMP(file) #else: # rw = SDL_RWFromObject(file) # # XXX Differ from pygame: don't freesrc when we didn't allocate it # surf = SDL_LoadBMP_RW(rw, 0) _img = JSConstructor(window.Image)() _img.src = file _img.canvas = html.CANVAS() def img_onload(*args): #http://www.jaypan.com/tutorial/javascript-passing-arguments-anonymous-functions-without-firing-function #the onload files very slow so variables get messed up so we have #to use args[0].path[0] to figure out the correct image console.log(args) if hasattr(args[0], 'target'): # Firefox this = args[0].target else: #chrome this = args[0].path[0] this.canvas.width = this.width this.canvas.height = this.height this.canvas.getContext('2d').drawImage(this, 0, 0) #this.loaded=True _img.onload = img_onload return _pygame_surface.Surface(surf=_img.canvas)
def __init__(self, dim=[], depth=16, surf=None): if surf is None: self._depth=depth self._canvas=html.CANVAS(width=dim[0], height=dim[1]) elif isinstance(surf, Surface): self._canvas=surf.copy() #self._width=surf.get_width() #self._height=surf.get_height() elif isinstance(surf, html.CANVAS): self._canvas=surf #self._width=surf.style.width #self._height=surf.style.height self._context=self._canvas.getContext('2d') self._canvas.id='layer_%s' % canvas_ID #setattr(self._canvas.style, 'z-index',canvas_ID) #setattr(self._canvas.style, 'position', 'relative') #setattr(self._canvas.style, 'left', '0px') #setattr(self._canvas.style, 'top', '0px') canvas_ID+=1
form <= html.DIV( html.LABEL('最大CP') + html.INPUT(type="number", name="最大CP", value="", Class="w3-input")) label3 = html.LABEL('屬性') input3 = html.SELECT(Class="w3-select") for option in ['...', '草、毒', '火', '水']: input3 <= html.OPTION(option) form <= html.DIV(label3 + input3) form <= html.P(html.BUTTON("上傳", Class="w3-button w3-red")) container <= form # 畫布 Html Canvas container <= html.DIV(html.H2('Html Canvas'), Class="w3-container w3-blue w3-margin-top") canvas = html.CANVAS(width=300, height=100) canvas.style = {"width": "100%"} ctx = canvas.getContext("2d") x = 20 def draw(event): global x ctx.beginPath() ctx.arc(x, 25, 15, 0, 2 * math.pi) x += 15 ctx.stroke() drawButton = html.BUTTON("畫圈", Class="w3-button w3-red").bind("click", draw) controls = html.DIV(drawButton)
from browser import html from javascript import JSConstructor # create an new canvas called new_canvas canvas = html.CANVAS() canvas.height = 800 canvas.width = 600 canvas.id = "new_canvas" doc <= canvas # use new_canvas to load stl part stlviewer = JSConstructor(STLViewer) stlviewer("/downloads/spikeball.stl", "new_canvas")
def fromstring(string, size, format, flipped=False): '''Create new Surface from a string buffer. This function takes arguments similar to _pygame_image.tostring(). The size argument is a pair of numbers representing the width and height. Once the new Surface is created you can destroy the string buffer. The size and format image must compute the exact same size as the passed string buffer. Otherwise an exception will be raised. :Parameters: `string` : str String containing image data. `size` : (int, int) Width, height of the image. `format` : str One of 'P', 'RGB', 'RGBA' or 'ARGB' `flipped` : bool If True, data is ordered from bottom row to top. :rtype: `Surface` ''' _img = html.IMG(width=size[0], height=size[1]) _img.src = string _canvas = html.CANVAS(width=size[0], height=size[1]) _ctx = _canvas.getContext('2d') _ctx.drawImage(_img, 0, 0) return _pygame_surface.Surface(surf=_canvas) width, height = size if format == 'P': Rmask = 0 Gmask = 0 Bmask = 0 Amask = 0 depth = 8 pitch = width elif format == 'RGB': if SDL_BYTEORDER == SDL_LIL_ENDIAN: Rmask = 0x000000ff Gmask = 0x0000ff00 Bmask = 0x00ff0000 else: Rmask = 0x00ff0000 Gmask = 0x0000ff00 Bmask = 0x000000ff Amask = 0x00000000 depth = 24 pitch = width * 3 elif format in ('RGBA', 'RGBX'): if SDL_BYTEORDER == SDL_LIL_ENDIAN: Rmask = 0x000000ff Gmask = 0x0000ff00 Bmask = 0x00ff0000 Amask = 0xff000000 else: Rmask = 0xff000000 Gmask = 0x00ff0000 Bmask = 0x0000ff00 Amask = 0x000000ff if format == 'RGBX': Amask = 0x00000000 depth = 32 pitch = width * 4 elif format == 'ARGB': if SDL_BYTEORDER == SDL_LIL_ENDIAN: Rmask = 0x0000ff00 Gmask = 0x00ff0000 Bmask = 0xff000000 Amask = 0x000000ff else: Rmask = 0x00ff0000 Gmask = 0x0000ff00 Bmask = 0x000000ff Amask = 0xff000000 depth = 32 pitch = width * 4 if len(string) != pitch * height: raise ValueError( 'String length does not equal format and resolution size') if flipped: string = ''.join([string[y*pitch:y*pitch+pitch] \ for y in range(height - 1, -1, -1)]) surf = SDL_CreateRGBSurfaceFrom(string, width, height, depth, pitch, Rmask, Gmask, Bmask, Amask) return _pygame_surface.Surface(surf=surf)
def __init__(self): OverlayPanel.__init__(self, "Right click to copy or save image") self.canvas = html.CANVAS(id="canvascopy") self <= self.canvas
def test_browser_html(): # First of all, the import of some libraries from browser import document from browser import html # All the elements will be inserted in the div with the "container" id container = document['container'] # We create a new div element newdiv = html.DIV(id="new-div") # Now we add some style newdiv.style = {"padding": "5px", "backgroundColor": "#ADD8E6"} # Now, lets add a table with a column with numbers and a # column with a word on each cell text = "Brython is really cool" textlist = text.split() table = html.TABLE() for i, word in enumerate(textlist): table <= html.TR(html.TD(i + 1) + html.TD(word)) # Now we add some style to the table table.style = { "padding": "5px", "backgroundColor": "#aaaaaa", "width": "100%" } # Now we add the table to the new div previously created newdiv <= table + html.BR() # a form? why not? form = html.FORM() input1 = html.INPUT(type="text", name="firstname", value="First name") input2 = html.INPUT(type="text", name="lastname", value="Last name") input3 = html.BUTTON("Button with no action!") form <= input1 + html.BR() + input2 + html.BR() + input3 newdiv <= form + html.BR() # Finally, we will add something more 'HTML5istic', a canvas with # a color gradient in the newdiv previously created and below the form canvas = html.CANVAS(width=300, height=300) canvas.style = {"width": "100%"} ctx = canvas.getContext('2d') ctx.rect(0, 0, 300, 300) grd = ctx.createRadialGradient(150, 150, 10, 150, 150, 150) grd.addColorStop(0, '#8ED6FF') grd.addColorStop(1, '#004CB3') ctx.fillStyle = grd ctx.fill() newdiv <= canvas # And finally we append the newdiv element # to the parent, in this case the div with the "container" id container <= newdiv """ browser.local_storage """ from browser.local_storage import storage storage['foo'] = 'bar' print(storage['foo']) del storage['foo'] with pytest.raises(KeyError): print(storage['foo']) # raises KeyError ## added exception handler
self._score_val[i].render(score=self._score[i]) def loadSettingsFromStorage(self): try: self._playSounds = self._storage['playSounds'] == "True" except: print("no playsounds in storage") # If we haven't stored a choice, the default is True self._playSounds = True def storePlaySoundsSetting(self): self._storage['playSounds'] = str(self._playSounds) # Use brython to create the canvas. real_canvas = html.CANVAS(width=CANVAS_WIDTH, height=CANVAS_HEIGHT, id='c') document <= real_canvas def windowChange(ev): print(window.innerWidth, window.innerHeight) window.bind('resize', windowChange) # Use the canvas in fabric canvas = fabric.Canvas.new('c', { 'width': CANVAS_WIDTH, 'height': CANVAS_HEIGHT, 'selectable': False,
ctx.lineWidth = 3 hour = now.hour % 12 + now.minute / 60 angle = hour * 2 * math.pi / 12 - math.pi / 2 needle(angle, 0.05, 0.5) minute = now.minute angle = minute * 2 * math.pi / 60 - math.pi / 2 needle(angle, 0.05, 0.85) ctx.lineWidth = 1 second = now.second + now.microsecond / 1000000 angle = second * 2 * math.pi / 60 - math.pi / 2 needle(angle, 0.05, 0.85, "#FF0000") # in red browser.timer.set_interval(set_clock, 100) canvas = html.CANVAS(id="pycanvas", width="250px", height="250px") doc['pydiv'] <= canvas # draw clock border ctx = canvas.getContext("2d") ctx.beginPath() ctx.lineWidth = 10 ctx.arc(width / 2, height / 2, ray, 0, 2 * math.pi) ctx.stroke() for i in range(60): ctx.lineWidth = 1 if i % 5 == 0: ctx.lineWidth = 3 angle = i * 2 * math.pi / 60 - math.pi / 3 x1 = width / 2 + ray * cos(angle)
from browser import document, html import math body = document.select("body")[0] canvas = html.CANVAS(width=400, height=400) body <= canvas context = canvas.getContext("2d") context.fillStyle = "white" def draw(event): if not event.buttons: return context.beginPath() context.arc(event.offsetX, event.offsetY, 40, 0, 2 * math.pi) context.fill() context.stroke() canvas.bind("mousedown", draw) canvas.bind("mousemove", draw)
def __init__(self): self.x = 250 self.y = 200 self.dir = 0 self.visible = True self.trail = True self.filling = False self.dest_x = self.x self.dest_y = self.y # the absolute angle in degrees self.dest_dir = self.dir self.prev_x = self.x self.prev_y = self.y self.stepSize = 20 self.angleStepSize = 10 self.commands = [] # kill any existing canvases if "turtle_canvas" in document: document["turtle_canvas"].remove() if "turtle_icon" in document: document["turtle_icon"].remove() self.width = 500 self.height = 400 # for the turtle canvas self.canvas = html.CANVAS(width = self.width, height = self.height, id="turtle_canvas") self.canvas.style= {"z-index": 2, "position": "absolute", "left":"0px", "right":"0px", "background-position": "center"} self.ctx = self.canvas.getContext('2d'); self.ctx.fillStyle= "rgba(0,0,0,0)" self.ctx.fillRect(0, 0, self.width, self.height) outputBox = document["outputBox"] outputBox <= self.canvas # for the turtle icon self.turtle = html.CANVAS(width = self.width, height = self.height, id="turtle_icon") self.turtle.style= {"z-index": 3, "position": "absolute", "left":"0px", "right":"0px", "background-position": "center"} self.turtle_ctx = self.turtle.getContext('2d'); self.turtle_ctx.fillStyle= "rgba(0,0,0,0)" self.turtle_ctx.fillRect(0, 0, self.width, self.height) outputBox = document["outputBox"] outputBox <= self.turtle self.array = None self.instant_render = False self.fill_path = [] self.r = 255 self.g = 255 self.b = 255 self.a = 1 self.fill_r = 255 self.fill_g = 255 self.fill_b = 255 self.fill_a = 1
<script type="text/python"> import spurmain from browser import document, html # 利用 Brython 的 document 建立一個 id 為 container 的 div 區域, 然後在其中放入對應的 html 標註 container = document['container'] # 3個齒輪的齒數 n1 = 17 n2 = 29 n3 = 15 # 根據繪圖的 3 個齒輪大小計算所需的畫布高度 height = 1.2*800*0.8/(int(n1)+int(n2)+int(n3))*max([int(n1), int(n2), int(n3)]) # 決定畫布的 id 字串 id = "gear" # 利用 Brython 的 html 方法建立 CANVAS canvas = html.CANVAS(id=id, width=800, height=height) # 將所建立的 canvas 畫布標註放入 container container <= canvas # m 為模數, 根據畫布的寬度, 計算適合的模數大小 # Module = mm of pitch diameter per tooth # 利用 80% 的畫布寬度進行繪圖 # 計算模數的對應尺寸 m = canvas.width*0.8/(n1+n2+n3+n4) m = canvas.width*0.8/(n1+n2+n3) # 根據齒數與模組計算各齒輪的節圓半徑 pr1 = n1*m/2 pr2 = n2*m/2 pr3 = n3*m/2