javascript - 在 Canvas 中动画绘制对象

标签 javascript html css canvas

所以我有一个绘制的对象:

enter image description here

它被放置在一个 block 中 enter image description here

我需要它使用 requestAnimationFrame() 方法为其设置动画,并在它从底部跳到顶部向右滑动时使用平移、旋转、缩放。

问题是我不知道如何将我制作的所有形状合并为一个(或如何制作动画)。

形状的代码是:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var counterClockwise = false;

ctx.beginPath();
ctx.lineWidth = "5";
ctx.strokeStyle = "white";
ctx.moveTo(10, 10);
ctx.lineTo(10, 100);
ctx.stroke();

ctx.beginPath();
ctx.arc(12, 38, 26, 4.7, Math.PI * .5, false);
ctx.lineWidth = "5";
ctx.strokeStyle = 'white';
ctx.stroke();

ctx.beginPath();
ctx.lineWidth = "5";
ctx.strokeStyle = "green";
ctx.moveTo(60, 10);
ctx.lineTo(40, 100);
ctx.stroke();

ctx.beginPath();
ctx.lineWidth = "5";
ctx.strokeStyle = "green";
ctx.moveTo(60, 10);
ctx.lineTo(80, 100);
ctx.stroke();

ctx.beginPath();
ctx.lineWidth = "5";
ctx.strokeStyle = "purple";
ctx.moveTo(80, 10);
ctx.bezierCurveTo(100, 145, 150, 100, 145, 10);
ctx.stroke();

ctx.beginPath();
ctx.lineWidth = "5";
ctx.strokeStyle = "cyan";
ctx.moveTo(160, 10);
ctx.lineTo(160, 95);
ctx.lineTo(200, 95);
ctx.stroke();
#myCanvas { background: #F00; }
<canvas id="myCanvas"></canvas>

提前致谢。

最佳答案

您可以使用 drawImage 在您的“输出” Canvas 上绘制另一个 Canvas 的内容(参见 MDN )。此示例显示如何使用 dWidthdHeight 参数缩放图像:

var c = document.getElementById("myCanvas");
var out = document.getElementById("out");
var ctx = c.getContext("2d");
var outCtx = out.getContext("2d");
var counterClockwise = false;
draw();

outCtx.drawImage(c, 0, 10, 150, 150) 

function draw() {
  ctx.beginPath();
  ctx.lineWidth = "5";
  ctx.strokeStyle = "white";
  ctx.moveTo(10, 10);
  ctx.lineTo(10, 100);
  ctx.stroke();

  ctx.beginPath();
  ctx.arc(12, 38, 26, 4.7, Math.PI * .5, false);
  ctx.lineWidth = "5";
  ctx.strokeStyle = 'white';
  ctx.stroke();

  ctx.beginPath();
  ctx.lineWidth = "5";
  ctx.strokeStyle = "green";
  ctx.moveTo(60, 10);
  ctx.lineTo(40, 100);
  ctx.stroke();

  ctx.beginPath();
  ctx.lineWidth = "5";
  ctx.strokeStyle = "green";
  ctx.moveTo(60, 10);
  ctx.lineTo(80, 100);
  ctx.stroke();

  ctx.beginPath();
  ctx.lineWidth = "5";
  ctx.strokeStyle = "purple";
  ctx.moveTo(80, 10);
  ctx.bezierCurveTo(100, 145, 150, 100, 145, 10);
  ctx.stroke();

  ctx.beginPath();
  ctx.lineWidth = "5";
  ctx.strokeStyle = "cyan";
  ctx.moveTo(160, 10);
  ctx.lineTo(160, 95);
  ctx.lineTo(200, 95);
  ctx.stroke();
}
canvas { background: #F00; }
<canvas id="myCanvas"></canvas>
<canvas id="out"></canvas>

关于javascript - 在 Canvas 中动画绘制对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41223531/

相关文章:

javascript - Layerslider 和使用超链接到弹出窗口

html - ionic 侧面菜单不显示内容

javascript - HTML 表单调用 javascript 函数

javascript - 在div顶部添加元素

html - MySQL 到 InnerHtml Angular 7

javascript - 链接到新页面时,让 parent 和 child 保持开放

javascript - 如何使用asp.net和html页面发送电子邮件

javascript - 如何创建漂亮的文本深度\阴影效果? (HTML)

javascript - 在下拉列表中添加图像

html - 文本对齐中心不起作用