如何使用HTML5的canvas属性

如何在画布上画矩形?

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>rect</title>
 6     <script type="text/javascript" src="canvas.js"></script>
 7 </head>
 8 <body onload="draw('canvas')">
 9 <canvas id="canvas" height="300" width="400"></canvas>
10 </body>
11 </html>
1 function draw(id) {
2     var canvas = document.getElementById(id);
3     var context = canvas.getContext('2d');
4     context.fillStyle = 'black';
5     context.strokeStyle = '#f60';
6     context.lineWidth = 5;
7     context.fillRect(0,0,400,300);
8     context.strokeRect(50,50,200,200);
9 }

如何画圆形?

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>circus</title>
 6     <script type="text/javascript" src="canvas.js"></script>
 7 </head>
 8 <body onload="draw('canvas')">
 9 <canvas  id="canvas" width="400" height="400"></canvas>
10 </body>
11 </html>
function draw(id) {
var canvas = document.getElementById(id);
var context = canvas.getContext('2d');

context.fillStyle = "#f1f2f3";
context.fillRect(0,0,400,400);

for (var i = 0; i < 10; i++){
context.beginPath();
var j = (i+1)*10;
context.arc(j*2,j*2,j,0,Math.PI*2,true);
context.closePath();

context.fillStyle = "rgba(255,0,0,0.25)";
context.fill();

context.strokeStyle = "red";
context.stroke();
}
}

原文地址:https://www.cnblogs.com/endymion/p/9102465.html