今天运用canvas实现了两个案例,一个是冒热气的杯子,一个是自动画圆。
一、冒热气的杯子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
box-sizing: border-box;
margin: 0;
padding: 0;
}
#canvas{
display: block;
margin: 100px auto;
border: 5px black solid;
}
</style>
</head>
<body>
<canvas id="canvas" width="1200px" height="800px">
您的浏览器不支持canvas,请升级。
</canvas>
</body>
<script>
/** @type {HTMLCanvasElement} */
var canvas = document.querySelector("#canvas");
var ctx = canvas.getContext('2d');
//四条气体
ctx.beginPath();
ctx.arc(500,200,25,Math.PI*1.5,Math.PI/2,true);
ctx.lineWidth = 4;
ctx.stroke();
ctx.arc(500,250,25,Math.PI*1.5,Math.PI/2,false);
ctx.lineWidth = 4;
ctx.stroke();
ctx.beginPath();
ctx.arc(550,200,25,Math.PI*1.5,Math.PI/2,true);
ctx.lineWidth = 4;
ctx.stroke();
ctx.arc(550,250,25,Math.PI*1.5,Math.PI/2,false);
ctx.lineWidth = 4;
ctx.stroke();
ctx.beginPath();
ctx.arc(600,200,25,Math.PI*1.5,Math.PI/2,true);
ctx.lineWidth = 4;
ctx.stroke();
ctx.arc(600,250,25,Math.PI*1.5,Math.PI/2,false);
ctx.lineWidth = 4;
ctx.stroke();
ctx.beginPath();
ctx.arc(650,200,25,Math.PI*1.5,Math.PI/2,true);
ctx.lineWidth = 4;
ctx.stroke();
ctx.arc(650,250,25,Math.PI*1.5,Math.PI/2,false);
ctx.lineWidth = 4;
ctx.stroke();
//杯身
ctx.beginPath();
ctx.moveTo(440,325);
ctx.lineTo(710,325);
ctx.lineTo(710,575);
ctx.lineTo(440,575);
ctx.lineTo(440,325);
ctx.strokeStyle = 'black';
ctx.lineWidth = 4;
ctx.fillStyle = 'red';
ctx.fill();
ctx.stroke();
//把手
ctx.beginPath();
ctx.arc(712,450,60,Math.PI*1.5,Math.PI/2,false);
ctx.strokeStyle = 'orange';
ctx.lineWidth = 10;
ctx.stroke();
</script>
</html>
二、自动画圆
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
box-sizing: border-box;
margin: 0;
padding: 0;
}
#canvas{
display: block;
margin: 100px auto;
border: 5px black solid;
}
</style>
</head>
<body>
<canvas id="canvas" width="1200px" height="800px">
您的浏览器不支持canvas,请升级。
</canvas>
</body>
<script>
/** @type {HTMLCanvasElement} */
var canvas = document.querySelector("#canvas");
var ctx = canvas.getContext('2d');
ctx.arc(600,400,100,0,Math.PI*2,false);
ctx.lineWidth = 10;
ctx.stroke();
ctx.closePath();
let deg=0;
function dawYuan(){
ctx.beginPath();
deg+=0.01;
ctx.arc(600,400,90,0,Math.PI*(0+deg),false);
ctx.strokeStyle = 'red';
ctx.lineWidth = 10;
ctx.stroke();
if(deg==2){
clearInterval(dawYuanJiShi);
}
}
let dawYuanJiShi = setInterval(dawYuan,20);
</script>
</html>