canvas基础讲解篇(二)

510 阅读1分钟

前段时间写了下《canvas基础讲解(一)juejin.cn/post/699473… 》,有些小伙伴还是有兴趣的,接着更新下这块内容,希望你看了对你有点收获,有什么不足或者建议希望大家在评论区提出。

绘制阴影效果

API讲解

  • shadowOffsetX -设置x轴的偏移
  • shadowOffsetY - 设置y轴上的偏移
  • shadowBlur -阴影模糊度
  • shadowColor - 阴影颜色

重点说明

代码实现

drawShadow() {
    this.ctx.shadowOffsetX = 5
    this.ctx.shadowOffsetY = 5
    this.ctx.shadowBlur = 10
    this.ctx.shadowColor = 'rgba(0, 0, 0, 0.5)'
    this.ctx.fillStyle = 'red'
    this.ctx.fillRect(0, 300, 200, 100)
}

效果截图

image.png

绘制渐变色

API讲解

  • createLinearGradient(x, y1, x2, y2) 其中(x1, y1)和(x2, y2)是两个坐标点,不同的坐标点对应不同的渐变色方向

重点说明

代码实现

// gradient
drawGradient() {
    const grd = this.ctx.createLinearGradient(0, 400, 400, 400)
    grd.addColorStop(0, '#4dffff')
    grd.addColorStop(1, '#8e12aa')
    this.ctx.fillStyle = grd
    this.ctx.font = 'bold 40px 微软雅黑'
    this.ctx.fillText('学习canvas', 0, 500)
}

效果截图

image.png

后记

canvas的使用基础大致就这些,其他的涉及到的是一些数学函数的运用、动画运用和图片处理等。 在开发过程中,我们要灵活运用这些基础知识去满足复杂的业务环境。