Canvas ur
- Forrige side Canvas billede
- Næste side Urkasse
I de følgende kapitler vil vi bygge en仿真时钟 ved hjælp af HTML canvas.
Del 1 - Opret canvas
Klokken har brug for en HTML container. Opret en HTML canvas:
HTML kode:
<!DOCTYPE html> <html> <body> <canvas id="canvas" width="400" height="400" style="background-color:#333"></canvas> <script> const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); let radius = canvas.height / 2; ctx.translate(radius, radius); radius = radius * 0.90 drawClock(); function drawClock() { ctx.arc(0, 0, radius, 0, 2 * Math.PI); ctx.fillStyle = "white"; ctx.fill(); } </script> </body> </html>
Kodeforklaring
Tilføj HTML <canvas> elementet til din side:
<canvas id="canvas" width="400" height="400" style="background-color:#333"></canvas>
Opret et canvasobjekt (const canvas):
const canvas = document.getElementById("canvas");
Opret et 2d tegneobjekt (const ctx) for canvasobjektet:
const ctx = canvas.getContext("2d");
Brug canvasets højde til at beregne klokkeens radius:
let radius = canvas.height / 2;
Advarsel
Brug canvasets højde til at beregne klokkeens radius, så klokken passer til alle canvasstørrelser.
Flyt (tegningsobjektets) (0,0) position tilbage til canvasets center:
ctx.translate(radius, radius);
Reducer klokkeens radius (til 90%) og tegn klokken inde i canvaset:
radius = radius * 0.90;
Opret en funktion til at tegne en klokke:
function drawClock() { ctx.arc(0, 0, radius, 0, 2 * Math.PI); ctx.fillStyle = "white"; ctx.fill(); }
Se også:
- Forrige side Canvas billede
- Næste side Urkasse