element .
In this tutorial we wi...">
On MDN there is a tutorial "2D game in pure JavaScript" , which studies the basics of using the HTML5 <canvas> element .
In this tutorial we will repeat the development of this game on Svelte.
In this example, we display three geometric shapes: a square, a rectangle, and a circle.
The canvas variable will be defined after the component is mounted in the DOM, so all the code is placed in the onMount lifecycle handler. The canvas element is bound to the canvas variable using the this binding .
<script> import { onMount } from 'svelte'; let canvas; onMount(() => { const ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.rect(20, 40, 50, 50); ctx.fillStyle = "#FF0000"; ctx.fill(); ctx.closePath(); ctx.beginPath(); ctx.arc(240, 160, 20, 0, Math.PI*2, false); ctx.fillStyle = "green"; ctx.fill(); ctx.closePath(); ctx.beginPath(); ctx.rect(160, 10, 100, 40); ctx.strokeStyle = "rgba(0, 0, 255, 0.5)"; ctx.stroke(); ctx.closePath(); }); </script> <canvas bind:this={canvas} width={480} height={320} ></canvas> <style> canvas { background: #eee; } </style>
Further we simply transfer all code without changes to the onMount () function. Comments are given only regarding the use of Svelte.
Pure JavaScript - Svelte
The special element <svelte: window> is used to listen for keyboard events. Keyboard event handlers and variables used in them are added outside the onMount () function.
Pure JavaScript - Svelte
A mouse event handler is also added outside of the onMount function.
As we can see, almost all of the code is transferred to the application on Svelte unchanged. Games usually do not write in pure JS, but use ready-made HTML5 frameworks. For example, the same game executed on the Phaser framework. You can see the experiments with WebGl on Svelte https://github.com/sveltejs/gl and ideas on svelte-gl https://github.com/Rich-Harris/svelte-gl .
Installing the game on the local computer:
git clone git@github.com:nomhoi/svelte-breakout-game.git cd svelte-breakout-game npm install npm run dev
Run the game in the browser at: http: // localhost: 5000 / .
Source: https://habr.com/ru/post/458142/
All Articles