Sintassi
- fillRect(x,y, w,h), colora l’interno del rettangolo
- (x,y) รจ l’angolo in alto a sinistra
- w, dimensione in orizzontale
- h, dimensione in verticale
- strokeRect(…), disegna il perimetro del rettangolo
- clearRect(…), pulisce/cancella i pixel nel rettangolo specificato
- rect(…), crea un oggetto rettangolo
Disegna un rettangolo
1 2 3 4 5 6 7 8 9 |
<canvas id="canvas1" style="border: 1px solid;" width="300" height="200"></canvas> <script> canvas=document.getElementById("canvas1"); g2d=canvas.getContext("2d"); w=canvas.width; h=canvas.height; w2=w/2; h2=h/2; g2d.fillStyle="#FF0000"; g2d.fillRect(0,0,w2,h2); </script> |
Disegna 4 rettangoli
1 2 3 4 5 6 7 8 9 10 11 12 |
<canvas id="canvas2" style="border: 1px solid;" width="300" height="200"></canvas> <script> canvas=document.getElementById("canvas2"); g2d=canvas.getContext("2d"); w=canvas.width; h=canvas.height; w2=w/2; h2=h/2; g2d.fillStyle="#FF0000"; g2d.fillRect( 0, 0, w2,h2); g2d.fillStyle="#00FF00"; g2d.fillRect(w2, 0, w2,h2); g2d.fillStyle="#0000FF"; g2d.fillRect( 0,h2, w2,h2); g2d.fillStyle="#000000"; g2d.fillRect(w2,h2, w2,h2); </script> |
Disegna un rettangolo al centro
1 2 3 4 5 6 7 8 9 10 11 |
<canvas id="canvas3" style="border: 1px solid;" width="300" height="200"></canvas> <script> canvas=document.getElementById("canvas3"); g2d=canvas.getContext("2d"); w=canvas.width; h=canvas.height; w2=w/2; h2=h/2; w4=w2/2; h4=h2/2; g2d.fillStyle="#FF0000"; g2d.fillRect(w2-w4,h2-h4,w2,h2); </script> |
Disegna 4 rettangoli su sfondo grigio e pulisce un rettangolo al centro
1 2 3 4 5 6 7 8 9 10 11 |
<canvas id="canvas31" style="background-color:gray; border: 1px solid;" width="300" height="200"></canvas> <script>canvas=document.getElementById("canvas31"); g2d=canvas.getContext("2d"); w=canvas.width;h=canvas.height; w2=w/2;h2=h/2; g2d.fillStyle="#FF0000";g2d.fillRect( 0, 0, w2,h2); g2d.fillStyle="#00FF00";g2d.fillRect(w2, 0, w2,h2); g2d.fillStyle="#0000FF";g2d.fillRect( 0,h2, w2,h2); g2d.fillStyle="#000000";g2d.fillRect(w2,h2, w2,h2); g2d.clearRect(w2-w4,h2-h4,w2,h2); </script> |
Disegna il perimetro del rettangolo al centro
1 2 3 4 5 6 7 8 9 10 |
<canvas id="canvas4" style="border: 1px solid;" width="300" height="200"></canvas> <script> canvas=document.getElementById("canvas4"); g2d=canvas.getContext("2d"); w=canvas.width; h=canvas.height; w2=w/2; h2=h/2; w4=w2/2; h4=h2/2; g2d.strokeRect(w2-w4,h2-h4,w2,h2); </script> |
Disegna una sequenza di rettangoli
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<canvas id="canvas5" style="border: 1px solid;" width="300" height="200"></canvas> <script> canvas=document.getElementById("canvas5"); w=canvas.width;h=canvas.height; w2=w/2;h2=h/2; wi=20;hi=10; delta=10; g2d=canvas.getContext("2d"); for(let i=1; i <= 15; i++) { g2d.strokeRect(w2-wi/2,h2-hi/2, wi,hi); wi += delta; hi += delta; } </script> |