【问题标题】:Rotating image on canvas around the center of the image [duplicate]围绕图像中心旋转画布上的图像[重复]
【发布时间】:2020-06-06 23:33:08
【问题描述】:

我想为我的图像的旋转设置动画。现在我的图像正在旋转,但在一个点附近。我想在不移动图像(围绕图像中心)的情况下制作动画。我希望你知道我的意思。这是我的代码的一部分:

ctx.save();
        ctx.translate(player.x+step, player.y+step);
        ctx.rotate(Math.radians(this.step%360));
        ctx.translate(-(player.x+step), -(player.y+step));

        ctx.drawImage(
            skeletonImage, 60, 65,
            this.width, this.height,
            this.x, this.y,
            this.width, this.height);

        ctx.restore();

每帧增加步长。

【问题讨论】:

    标签: javascript html canvas


    【解决方案1】:

    您可以将画布平移到您想要绘制的位置,在该点旋转画布,然后使用以下调用绘制图像:

    ctx.drawImage(
      img, 
      img.width / -2,   // x
      img.height / -2,  // y
      img.width,
      img.height
    );
    

    xy分别从中心移开一半的宽度和高度,将图像的中心(width / 2height / 2)置于画布上的0、0(旋转点) .

    这是一个最小的完整示例:

    const degToRad = deg => deg * Math.PI / 180;
    const canvas = document.createElement("canvas");
    document.body.appendChild(canvas);
    canvas.width = canvas.height = 180;
    const ctx = canvas.getContext("2d");
    const player = {
      x: canvas.width / 2, 
      y: canvas.height / 2, 
      angle: 0,
      img: new Image()
    };
    player.img.onload = function () {
      (function update() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.save();
        ctx.translate(player.x, player.x);
        ctx.rotate(degToRad(player.angle++ % 360));
        ctx.drawImage(
          player.img, 
          player.img.width / -2, 
          player.img.height / -2, 
          player.img.width, 
          player.img.height
        );
        ctx.restore();  
        requestAnimationFrame(update);
      })();
    };
    player.img.src = "http://placekitten.com/100/100";

    虽然我不确定您的游戏的具体细节是什么,但我会将step 排除在渲染计算之外。纯粹使用它来更新位置,然后仅在计算出实体的所有新位置时才渲染。将步长、速度等排除在渲染阶段之外。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-19
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      相关资源
      最近更新 更多