Canvas-概念补充

203 阅读2分钟

Canvas-编程思维

canvas像素化

因为canvas的体积会更加的轻量,与其它不同的是,在绘制完成图形后,立马会被像素化,开发者无法再从画布中得到绘制的元素,无法在像css+html或falsh那样,可以在运行时更改其内容。

动画逻辑

canvas的动画思维:清屏-->更新-->渲染-->清屏……这样不断的重复此逻辑,换句话说,就是重新再画一次,学过flash动画的都知道,动画不过也就是一帧一帧的在切换图片,只不过速度快到一定程度后,就成了动画。

此段代码可以使矩形,不断的在左右最往复运动

      const canvas = document.getElementById("container");
      const context = canvas.getContext("2d");
      let x = 10;
      context.fillRect(x, 10, 200, 200);
      setInterval(() => {
        x++;
        context.clearRect(0, 0, 1000, 600);
        context.fillRect(x, 10, 200, 200);
        console.log(x);
        if (x >= 750) {
          x = 10;
        }
      }, 10);

image.png

canvas面向对象

因为 canvas 不能获取已经绘制完成的对象,所以我们要维持对象的状态。在 canvas 动画中,我们都使用面向对象来进行编程,因为我们可以使用面向对象的方式来维持canvas 需要的属性和状态,下面请看一个例子,最终会得到一个缓慢移动的闪烁方块儿。

      class Rect {
        x;
        y;
        width;
        height;
        color;
        context;
        constructor(context, config) {
          this.context = context;
          this.x = config.x;
          this.y = config.y;
          this.width = config.width;
          this.height = config.height;
          this.color = config.color;
          const { x, y, width, height, color } = config;
          this.render(x, y, width, height, color);
        }

        render(x, y, width, height, color) {
          this.context.clearRect(0, 0, 1000, 600);
          this.context.fillStyle = color;
          this.context.fillRect(x, y, width, height);
        }
      }
      function getRandomInt(min, max) {
        min = Math.floor(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min + 1)) + min;
      }
      //创建一个矩形
      const canvas = document.getElementById("container");
      const context = canvas.getContext("2d");
      let x = 10;
      // 实例化一个矩形
      const r1 = new Rect(context, {
        x: x,
        y: 10,
        width: 100,
        height: 100,
        color: "skyblue",
      });
      const colors = ["red", "blue", "green", "yellow", "orange", "purple"];
      // 缓慢移动矩形,实际上就是在不断的清除和渲染,不断往复
      setInterval(() => {
        x += 2;
        r1.render(x, 10, 100, 100, colors[getRandomInt(0, colors.length - 1)]);

        if (x >= 800) {
          x = 10;
        }
      }, 50);

image.png

内容回顾

  1. 因为canvas的特性,会使绘制完成的图形马上像素化,所以需要使图形元素对象持久化,使用面向对象编程方式。
  2. canvas运动逻辑本质上是在不断的清除重绘,清除重绘。