<style>
#can{
width: 500px;
height: 300px;
border: 1px solid #000;
}
</style>
<!-- 画布 -->
<canvas id="can" width="500px" height="300px"></canvas>
<script>
let canvas = document.getElementById('can')
let ctx = canvas.getContext('2d')
</script>
1.画线
//画线
ctx.lineWidth = 10
ctx.moveTo(100,100)
ctx.lineTo(200,100)
ctx.lineTo(200,200)
ctx.stroke()
ctx.beginPath()
ctx.lineWidth = 5
ctx.moveTo(200,200)
ctx.lineTo(100,200)
ctx.lineTo(100,300)
ctx.closePath()
ctx.stroke()
ctx.fill()
2.画矩形
ctx.rect(100,100,200,100)
ctx.stroke()
ctx.fill()
ctx.strokeRect(100,100,200,100)
ctx.fillRect(100,100,200,100)
// 练习:方块下落
let height = 100
let timer = setInterval(function(){
ctx.clearRect(0,0,500,300)
ctx.strokeRect(100,height,50,50)
height += 2
},1000/60)
3.画圆
ctx.arc(100,100,50,0,Math.PI*1.8,0 ) // 圆心(x,y),半径(r),弧度(起始弧度,结束弧度),方向(顺时针,逆时针)
ctx.lineTo(100,100)
ctx.closePath()
ctx.stroke()
ctx.fill()
4.圆角矩形
ctx.moveTo(100,110)
ctx.arcTo(100,200,200,200,10) // B(x,y) C(x,y) 圆角大小
ctx.arcTo(200,200,200,100,10)
ctx.arcTo(200,100,100,100,10)
ctx.arcTo(100,100,100,200,10)
ctx.stroke()
ctx.fill()
5.贝塞尔曲线
ctx.beginPath();
ctx.moveTo(100,100)
// ctx.quadraticCurveTo(200,200,300,100) //绘制二次贝塞尔曲线
ctx.bezierCurveTo(200,200,300,100,400,200) //绘制三次贝塞尔曲线
ctx.stroke()
// 贝塞尔曲线练习
let width = 500;
let height = 300;
let offset = 0;
let num = 0;
setInterval(function(){
ctx.clearRect(0,0,500,300)
ctx.beginPath()
ctx.moveTo(0+offset-500,height/2)
ctx.quadraticCurveTo(width/4+offset-500,height/2+Math.sin(num)*120,width/2+offset-500,height/2)
ctx.quadraticCurveTo(width/4*3+offset-500,height/2-Math.sin(num)*120,width+offset-500,height/2)
ctx.moveTo(0+offset,height/2)
ctx.quadraticCurveTo(width/4+offset,height/2+Math.sin(num)*120,width/2+offset,height/2)
ctx.quadraticCurveTo(width/4*3+offset,height/2-Math.sin(num)*120,width+offset,height/2)
ctx.stroke()
offset +=5
offset %=500
num +=0.02
},1000/30)
|