javascript - 如何在 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 中的动画
解决方案
您需要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>
推荐阅读
- variables - 通过引用另一个变量来分配变量
- mysql - 如何将一个列/表中的多个日期的逻辑应用于另一列/表中的多个日期?
- phpunit - Travis CI 是否检查多个 .travis.yml 文件?
- google-app-engine - 将 Google App Engine 作为 PHP 命令行运行?
- pycharm - 双击选择整个驼峰式单词?
- java - 使用 Java 组合来自多个 RDD 的数据
- neural-network - 3 层神经网络无法正确学习
- drone - 多步并行阶段的配置
- php - 我如何上传文件 Curl PHP
- node.js - Nodejs:错误的回调顺序