1.Canvas 常用 api

获取 2d 上下文对象

let ctx = document.getElementById("canva").getContext("2d");

globalCompositeOperation

图形组合方式的设置

ctx.globalCompositeOperation = "destination-over";//新生成的图像在上方

image.png

填充和背景

// 3.设置背景填充色和边框色
ctx.fillStyle = "rgba(0,0,0,0.4)";
ctx.strokeStyle = "rgba(0,153,255,0.4)";

位移

// 5.设置位移
ctx.translate(150, 150);

旋转

旋转只传入一个参数:旋转的角度

// 6.1 地球旋转
ctx.rotate(
    ((2 * Math.PI) / 60) * time.getSeconds() +
    ((2 * Math.PI) / 60000) * time.getMilliseconds()
);

画一幅天文图

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <canvas id="canva" width="500" height="500"></canvas>
  </body>
  <script type="text/javascript">

    let sun;
    let earth;
    let moon;
    let ctx;

    function init() {
      sun = new Image();
      earth = new Image();
      moon = new Image();
      sun.src = "./sun.png";
      earth.src = "./earth.png";
      moon.src = "./moon.png";

      let canvas = document.querySelector("#canva");
      ctx = canvas.getContext("2d");

      sun.onload = function () {
        draw();
      };
    }
    init();
    function draw() {
      ctx.clearRect(0, 0, 300, 300); //清空所有的内容
      // 绘制太阳
      ctx.drawImage(sun, 0, 0, 300, 300);
      // 保存当前 Canvas 状态
      ctx.save();
      // 将画布起始位置移动到圆心的位置
      ctx.translate(150, 150);

      //绘制earth轨道
      ctx.beginPath();
      ctx.strokeStyle = "rgba(255,255,0,0.5)";
      // 画一个半径 100 的圆
      ctx.arc(0, 0, 100, 0, 2 * Math.PI);
      // 描绘
      ctx.stroke();

      let time = new Date();
      //画布再次右移,从 -> 方向开始绘制地球
      ctx.rotate(
        ((2 * Math.PI) / 60) * time.getSeconds() +
          ((2 * Math.PI) / 60000) * time.getMilliseconds()
      );
      ctx.translate(100, 0);
      ctx.drawImage(earth, -12, -12);

      //绘制月球轨道
      ctx.beginPath();
      ctx.strokeStyle = "rgba(255,255,255,.3)";
      ctx.arc(0, 0, 40, 0, 2 * Math.PI);
      ctx.stroke();

      //绘制月球
      ctx.rotate(
        ((2 * Math.PI) / 6) * time.getSeconds() +
          ((2 * Math.PI) / 6000) * time.getMilliseconds()
      );
      // 同理月球起始位置也要右移 40
      ctx.translate(40, 0);
      ctx.drawImage(moon, -3.5, -3.5);
      ctx.restore();
      // 回到上一个 Canvas 状态
      requestAnimationFrame(draw);
    }
  </script>
</html>

image.png


逃跑计划
8 声望1 粉丝

一个前端


« 上一篇
webpack 配置
下一篇 »
HTTP 协议