画笔的一些方法:
addColorStop(n, color):指定颜色停止,n可以是0至1.
ctx.createLinearGradient(x, y, x1, y1):线性渐变
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
// 创建渐变
var grd=ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
// 填充渐变
// 可以把内容填充改为描边填充
ctx.fillStyle=grd;
ctx.fillRect(10,10,150,80);
ctx.createRadialGradient(x, y, r, x1, y1, r1):径向渐变
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
// 先创建好径向渐变
var grd=ctx.createRadialGradient(75,50,5,90,60,100);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
// 填充内容渐变
ctx.fillStyle=grd;
ctx.fillRect(10,10,150,80);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
canvas {
display: block;
/* background-color: #eee; */
margin: 100px auto;
}
</style>
<title>Document</title>
</head>
<body>
<canvas width="500" height="500"></canvas>
<script>
// 获取画布
let canvas = document.querySelector('canvas')
// 获取画笔
let ctx = canvas.getContext('2d')
// 平移坐标系
ctx.translate(250, 250)
// 画表盘
ctx.arc(0, 0, 240, 0, Math.PI * 2)
ctx.stroke()
// 画刻度
for (let i = 0; i < 60; i++) {
ctx.beginPath()
ctx.moveTo(i % 5 === 0 ? 210 : 225, 0)
ctx.lineTo(240, 0)
ctx.lineWidth = i % 5 === 0 ? 4 : 2
ctx.stroke()
ctx.rotate(Math.PI / 30)
}
// 画字
// 设置字体
ctx.font = '30px Arial'
// 设置水平居中
ctx.textAlign = 'center'
// 设置垂直居中
ctx.textBaseline = 'middle'
// 设置文本
ctx.strokeText('12', 0, -190)
ctx.strokeText('3', 190, 0)
ctx.strokeText('6', 0, 190)
ctx.strokeText('9', -190, 0)
// 将坐标轴逆时针旋转90度 方便指针操作
ctx.rotate(-Math.PI / 2)
// 保存当前坐标系的设定
ctx.save()
// 对时分秒指针的操作
function aTime() {
// 擦除(填充)
ctx.beginPath()
// 设置填充样式颜色
ctx.fillStyle = '#fff'
ctx.arc(0, 0, 150, 0, Math.PI * 2)
// 填充
ctx.fill()
// 获取时间
let time = new Date()
let hour = time.getHours()
let minutes = time.getMinutes()
let seconds = time.getSeconds()
// 时针
ctx.rotate(hour * (Math.PI / 6) + minutes / 60 * Math.PI / 6)
ctx.beginPath();
ctx.moveTo(-20, 0);
ctx.lineTo(100, 0);
ctx.lineWidth = 8;
ctx.strokeStyle = 'black';
ctx.stroke()
// restore重置一次会消耗一次save
ctx.restore()
ctx.save()
console.log(hour);
// 分针
ctx.rotate(minutes * (Math.PI / 30) + seconds / 60 * Math.PI / 30)
ctx.beginPath()
ctx.moveTo(-35, 0)
ctx.lineTo(120, 0)
ctx.lineWidth = 4
ctx.strokeStyle = 'cyan'
ctx.stroke()
// restore重置一次会消耗一次save
ctx.restore()
ctx.save()
// 秒针
ctx.rotate(seconds * (Math.PI / 30))
ctx.beginPath()
ctx.moveTo(-50, 0)
ctx.lineTo(150, 0)
ctx.lineWidth = 2;
ctx.strokeStyle = 'red'
ctx.stroke()
// restore重置一次会消耗一次save
ctx.restore()
ctx.save()
// 设置圆心轴
ctx.beginPath()
ctx.arc(0, 0, 10, 0, Math.PI * 2)
ctx.lineWidth = 6
ctx.strokeStyle = 'gold'
ctx.stroke()
ctx.fillStyle = '#eee'
// 填充
ctx.fill()
}
setInterval(aTime, 1000)
</script>
</body>
</html>