1.画圆以及圆弧
<style>canvas {margin: 0 auto;border: 2px solid #aaa;display: block; /*画布居中*/}</style><body><canvas id="cont" width="500px" height="500px">Hello Canvas</canvas> <script>var canvas = document.querySelector("#cont");//获取画布上下文var ctx = canvas.getContext('2d');//画圆ctx.beginPath();ctx.arc(250, 250, 150, 0, Math.PI*2, false);ctx.fillStyle = 'gold';ctx.fill();ctx.lineWidth = 3;ctx.strokeStyle = 'purple';ctx.stroke();//此处会自动加上closePath();//画圆弧ctx.beginPath();ctx.arc(50, 50, 50, 0, Math.PI, true);ctx.stroke();//此处会自动加上closePath();</script></body>
结果如图
2.画随机统计图
<style>canvas {margin: 0 auto;border: 2px solid #aaa;display: block; /*画布居中*/}</style><body><canvas id="cont" width="500px" height="500px">Hello Canvas</canvas><script>var canvas = document.querySelector("#cont");//获取画布上下文var ctx = canvas.getContext('2d');//画坐标轴ctx.beginPath();ctx.moveTo(100, 100);ctx.lineTo(100, 400);ctx.lineTo(400, 400);ctx.stroke();ctx.closePath();/*ctx.fillRect(160, 200, 20, 200); //长方形左上角坐标以及长方形宽高ctx.fillRect(200, 200, 20, 200);*/for (var i = 0; i < 5; i++) {var height = Math.random()*280 + 10; //[10, 290]//方法一:随机颜色,#后面拼接一个随机十六进制字符// ctx.fillStyle = '#'+parseInt(Math.random()*0xffffff).toString(16);//方法二:ctx.fillStyle = 'rgb(' + parseInt(Math.random()*256) + ',' + parseInt(Math.random() * 256) +',' + parseInt(Math.random() * 256) + ')';ctx.fillRect(160+i*40, 400-height, 20, height); }</script></body>
结果如图
3.清除画布
<style>canvas {margin: 0 auto;border: 2px solid #aaa;display: block; /*画布居中*/}</style><body><canvas id="cont" width="500px" height="500px">Hello Canvas</canvas> <script>var canvas = document.querySelector("#cont");//获取画布上下文var ctx = canvas.getContext('2d');ctx.rect(100, 100, 300, 200);//绿色矩形左上角的坐标以及宽高//填充ctx.fillStyle= 'green';ctx.fill();//描边ctx.strokeStyle = 'red';ctx.lineWidth = 5;ctx.stroke();//清除画布ctx.clearRect(120, 120, 180, 180); //左上角x、y的坐标,要清除的宽高</script></body>
结果如图