5.canvas 优化

1.离屏渲染

const WIDTH = document.documentElement.clientWidth;
const HEIGHT = document.documentElement.clientHeight;
const CANVAS = document.getElementById('canvas');
canvas.setAttribute("width", WIDTH);
canvas.setAttribute("height", HEIGHT);
const ctx = CANVAS.getContext('2d');
const NUM = rand(200, 300);
const SSC = 'white';
let snowArr = [];
const cacheCanvas = document.createElement("canvas");
cacheCanvas.setAttribute("width", WIDTH);
cacheCanvas.setAttribute("height", HEIGHT);
const cacheCtx = cacheCanvas.getContext("2d");

/**
 * 随机值
 * @param {number} rMin 
 * @param {number} rMax 
 */
function rand (rMin, rMax) {
  return ~~((Math.random() * (rMax - rMin) + rMin))
}

/**
 * requestAnimatonFrame兼容
 */
window.requestAnimationFrame = (function() {
  return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    function(cb) {
      window.setTimeout(cb, 1E3 / 60);
    }
})();


/**
 * 单个雪花
 * @param {number} x x位置
 * @param {number} y y位置
 * @param {number} sr 半径
 * @param {number} sx x方向速度
 * @param {number} sy y方向速度
 */
class Snow {
  constructor() {
    this.x = rand(0, WIDTH);
    this.y = rand(0, HEIGHT/ 2);
    this.sr = rand(1,3);
    this.sx = rand(-2,2);
    this.sy = rand(1,4);
  }
  draw() {
      cacheCtx.beginPath();
      cacheCtx.arc(this.x,this.y,this.sr,0,Math.PI * 2,true);
      cacheCtx.fillStyle = '#fff';
      cacheCtx.fill();
      cacheCtx.closePath();
  }
  move() {
    this.x = this.x + this.sx;
    this.y = this.y + this.sy;
    if(this.x < 0 || this.x > CANVAS.width || this.y > CANVAS.height) {
      this.x = rand(0, WIDTH);
      this.y = rand(0, HEIGHT/ 5);
    }
    this.draw()
  }
}

for(let i = 0; i < NUM; i++){
  let snow = new Snow();
  snowArr.push(snow);
}

function init () { 
  cacheCtx.clearRect(0,0,CANVAS.width,CANVAS.height);
  requestAnimationFrame(init)

  snowArr.forEach( (snow) => {
    snow.move();
  });

  //将离屏画布画到真实画布上
  ctx.clearRect(0,0,CANVAS.width,CANVAS.height);
  ctx.drawImage(cacheCanvas,0,0)
}

init();

2.避免浮点数的坐标点,使用整数

ctx.drawImage(myImage, 0.3, 0.5);

此时应使用Math.floor()取整

3.不要在用drawImage时缩放图像

4.关闭透明度

var ctx = canvas.getContext('2d', { alpha: false });

你可能感兴趣的:(5.canvas 优化)