使用纯Canvas实现一个按钮点击按下的效果,类似下图
效果使用到的API
阴影偏移:
shadowOffsetX = float
shadowOffsetY = float
- 用来实现有体积的视觉效果 效果等同于
css
中的shadow
属性
阴影模糊:
shadowBlur = float
- 设置阴影的模糊效果
阴影颜色:
shadowColor = color
- 设置阴影的颜色
路径:
beginPath()
moveTo()
lineTo()
quadraticCurveTo()
closePath()
- 以此为
起始一条路径,或重置当前路径
、把路径移动到画布中的指定点,不创建线条
、添加一个新点,然后在画布中创建从该点到最后指定点的线条
、创建二次贝塞尔曲线
、创建从当前点回到起始点的路径
具体实现:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="1000" height="800" style="border:1px solid #d3d3d3;"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var x = 20
var y = 20
var height = 100
var width = 200
var radius = 5
// 绘制初始状态
radiusRect(x, y, width, height, radius, ctx)
setShadow(ctx)
draw(ctx)
cleartShadow(ctx)
// 绘制圆角矩形
function radiusRect(x, y, width, height, radius, ctx) {
// 开启路径
ctx.beginPath()
// 设置填充颜色
ctx.fillStyle = "#0066CC"
// 绘制边
ctx.moveTo(x, y + radius)
ctx.lineTo(x, y + height - radius)
// 绘制圆角
ctx.quadraticCurveTo(x, y + height, x + radius, y + height)
ctx.lineTo(x + width - radius, y + height)
ctx.quadraticCurveTo(x + width, y + height, x + width, y + height - radius)
ctx.lineTo(x + width, y + radius)
ctx.quadraticCurveTo(x + width, y, x + width - radius, y)
ctx.lineTo(x + radius, y)
ctx.quadraticCurveTo(x, y, x, y + radius)
// 闭合路径
ctx.closePath();
}
// 设置阴影和偏移
function setShadow(ctx) {
ctx.shadowOffsetX = 0
ctx.shadowOffsetY = 10 // 10个偏移量
ctx.shadowBlur = 0
ctx.shadowColor = "#006600"
}
// 清楚掉阴影和位移
function cleartShadow(ctx) {
ctx.shadowOffsetX = 0
ctx.shadowOffsetY = 0
}
// 绘制到画布上
function draw(ctx) {
ctx.stroke()
ctx.fill()
}
//事件监听 按下时,持续的绘制为按下状态
c.addEventListener('mousedown', (e) => {
if (e.clientX >= x && e.clientX <= x + width && e.clientY >= y && e.clientY <= y + height && e
.button == 0) {
ctx.clearRect(0, 0, 1000, 1000) // 先清楚所有的矩形
radiusRect(x, y + 10, width, height, radius, ctx) // 10个偏移量
draw(ctx)
}
})
//事件监听 抬起时,恢复为初始状态
c.addEventListener('mouseup', (e) => {
if (e.button == 0) {
setTimeout(() => {
radiusRect(x, y, width, height, radius, ctx)
setShadow(ctx)
draw(ctx)
cleartShadow(ctx)
}, 100)
}
})
</script>
</body>
</html>
网友评论