1、绘制矩形
<!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>Canvas</title>
</head>
<body>
<div>hhhhhhh</div>
<canvas id="drawing" width="400" height="400" style="border:1px solid #000000;">canvas hhhhhh</canvas>
<script>
let drawing = document.getElementById('drawing')
if(drawing.getContext){
//获取对绘图上下文的引用
let context = drawing.getContext("2d")
//取得图像的数据UR
// let imgUrl = drawing.toDataURL("image/png")
//显示图片
// let image = document.createElement("img")
// img.src = imgUrl
// document.body.appendChild(image)
//描边
context.strokeStyle = "red"
context.strokeRect(10,10,50,50)
//填充
context.fillStyle = "blue"
context.fillRect(30,30,50,50)
//擦除画布中某个区域
context.clearRect(40,40,10,10)
}
</script>
</body>
</html>
2、绘制路径,绘制文本
//获取对绘图上下文的引用
let context = drawing.getContext("2d")
context.beginPath()//创建路径
//绘制外圆,以坐标(100,100)为起点,以99为半径绘制一条弧线,从0弧度绘制到2PI弧度,顺时针计算起始角度和结束角度
context.arc(100,100,99,0,2*Math.PI,false)
context.arc(100,100,94,0,2*Math.PI,false)//绘制内圆
//绘制分针
context.moveTo(100,100) //移动绘制光标到(x,y)
context.lineTo(100,15)//绘制一条从上一点到(x,y)的直线
// 绘制时针
context.moveTo(100,100)
context.lineTo(35,100)
// 描画路径
context.stroke()
// 绘制文本
context.font="bold 14px Arial"
context.textAlign="center"
context.textBaseline = "middle"
context.fillText("12",100,20)
//与开头对齐
context.textAlign="start"
context.fillText("12",100,40)
// 与末尾对齐
context.textAlign="end"
context.fillText("12",100,60)
3、变换、旋转
let context = drawing.getContext("2d")
context.beginPath()//创建路径
//绘制外圆,以坐标(100,100)为起点,以99为半径绘制一条弧线,从0弧度绘制到2PI弧度,顺时针计算起始角度和结束角度
context.arc(100,100,99,0,2*Math.PI,false)
context.moveTo(194,100)
context.arc(100,100,94,0,2*Math.PI,false)//绘制内圆
//移动原点到表盘中心
context.translate(100,100)
//旋转表针
context.rotate(1)
//绘制分针
context.moveTo(0,0) //移动绘制光标到(x,y)
context.lineTo(0,-85)//绘制一条从上一点到(x,y)的直线
// 绘制时针
context.moveTo(0,0)
context.lineTo(-65,0)
// 描画路径
context.stroke()
4、绘制阴影
let context = drawing.getContext("2d")
// 设置阴影
context.shadowOffsetX = 5
context.shadowOffsetY = 5
context.shadowBlur = 4 //阴影模糊量,默认为0,表示不模糊
context.shadowColor = "rgba(0,0,0,0.5)" //阴影颜色
//描边
context.strokeStyle = "red"
context.strokeRect(10,10,50,50)
//填充
context.fillStyle = "blue"
context.fillRect(30,30,50,50)
5、绘制渐变
// 设置渐变
let gradient = context.createLinearGradient(30,30,70,70)
gradient.addColorStop(0,"white")
gradient.addColorStop(1,"black")
//描边
context.strokeStyle = "red"
context.strokeRect(10,10,50,50)
//填充
// context.fillStyle = "blue"
context.fillStyle = gradient
context.fillRect(30,30,50,50)
径向渐变
let gradient = context.createRadialGradient(50,50,10,55,55,30)//径向渐变
gradient.addColorStop(0,"white")
gradient.addColorStop(1,"black")
//描边
context.strokeStyle = "red"
context.strokeRect(10,10,50,50)
//填充
// context.fillStyle = "blue"
context.fillStyle = gradient
context.fillRect(30,30,50,50)