创建 anemones.ts 文件

    canvas 里面的坐标轴体系。

    绘制海葵 - 图1

    这里的海葵我们从下往上画。

    绘制海葵 - 图2

    而对于如何计算,看这幅图,聪明的你应该能理解。

    1. import { ctx_two, cvs_height } from "./init";
    2. class Anemones{
    3. x: number[] = []; // x 轴的坐标
    4. height: number[] = []; // 高度
    5. num = 50; // 绘制数量
    6. constructor(){
    7. }
    8. /**
    9. * 其实就跟在 PS 里面画一样,只不过都是通过代码进行操作,不能通过鼠标进行操作。
    10. *
    11. * save() - restore() 做作用就是只对他们之间的代码应用这些画笔样式
    12. *
    13. * save() 就相当于暂存一下画笔的状态。开启一个快照,可以对这个快照进行任何操作
    14. *
    15. * restore() 恢复之前画笔的状态
    16. */
    17. draw(){
    18. ctx_two.save() // 暂存画笔状态
    19. // 设置画笔样式
    20. ctx_two.globalAlpha = 0.6 // 设置透明度
    21. ctx_two.strokeStyle = '#3b154e' // 设置画笔颜色
    22. ctx_two.lineWidth = 20; // 画笔的宽度
    23. ctx_two.lineCap = "round" // 圆角的线
    24. for (let i = 0; i < this.num; ++i) {
    25. ctx_two.beginPath() // 开始绘画
    26. ctx_two.moveTo(this.x[i], cvs_height) // 把画笔移动到 x 点,画布的最下方出,从下往上画海葵
    27. ctx_two.lineTo(this.x[i], cvs_height - this.height[i]) // 画到 cvs_height - this.height[i] 的地方为止
    28. ctx_two.stroke() // 确认,开始渲染
    29. }
    30. ctx_two.restore() // 恢复之前暂存的画笔状态
    31. }
    32. /**
    33. * 初始化海葵的 x 坐标和高度
    34. */
    35. init(){
    36. for (let i = 0; i < this.num; ++i) {
    37. this.x[i] = i * 16 + Math.random() * 20;
    38. this.height[i] = 200 + Math.random() * 50;
    39. }
    40. }
    41. }
    42. const ane = new Anemones();
    43. export default ane;
    1. // init.ts
    2. import ane from "./anemones";
    3. function init() {
    4. ane.init()
    5. }
    1. // game-loop.ts
    2. import ane from "./anemones";
    3. function gameLoop() {
    4. ane.draw()
    5. }

    绘制海葵 - 图3

    此时你的游戏应该像这样。