首页 > 解决方案 > 如何在 HTML 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 canvas 中的动画

标签: javascriptanimationhtml5-canvas

解决方案


您需要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>


推荐阅读