如何在HTML Canvas中转换整个函数?

时间:2018-12-24 12:11:27

标签: javascript animation html5-canvas

我想使狗的头旋转,但我不知道如何选择整个功能,而不能选择更多功能并将其转换为动画。

// The function
Head();

rotate();
// this is for the entire canvas, but how to do it specifically for a function
context.rotate(rotation);

rotation += 0.04

我对HTML画布中的动画也不是很熟悉

1 个答案:

答案 0 :(得分:1)

在转换之前,您需要save()上下文。接下来,调用绘制头部的函数。然后,您restore()上下文。这样,头部将变成螺母,而不是画布的其余部分。

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let cw = canvas.width = 300,
  cx = cw / 2;
let ch = canvas.height = 300,
  cy = ch / 2;

let rotation = 0

function background(){
  ctx.beginPath();
  ctx.fillStyle="gold";
  ctx.fillRect(20,20,160,50);
  
  ctx.beginPath();
  ctx.fillStyle="gold";
  ctx.fillRect(120,220,160,50);
}

function Head(){
  ctx.fillStyle = "skyBlue";
  ctx.beginPath();
  ctx.arc(0,0,40,0,2*Math.PI);
  ctx.fill();
  
  ctx.beginPath();
  ctx.arc(-15,-5,8,0,2*Math.PI);
  ctx.fillStyle="white";
  ctx.fill();
  
  ctx.beginPath();
  ctx.arc(15,-5,8,0,2*Math.PI);
  ctx.fillStyle="white";
  ctx.fill();
  
  ctx.beginPath();
  ctx.arc(0,0,30,Math.PI/10,9*Math.PI/10);
  ctx.strokeStyle="white";
  ctx.stroke();
}

function frame(){
  requestAnimationFrame(frame);
  rotation += 0.04;
  ctx.clearRect(-cw,-ch,2*cw,2*ch);
  background()
  ctx.save();
  ctx.translate(cx,cy);
  ctx.rotate(rotation);
  // The function
  Head();
  ctx.restore();
}

frame()
canvas{border:1px solid}
<canvas id="canvas"></canvas>