【问题标题】:How to draw a moving repeating pattern on an html5 canvas如何在 html5 画布上绘制移动的重复图案
【发布时间】:2017-05-11 14:44:46
【问题描述】:

我有一面墙,它在 HTML5 画布上绘制在屏幕上从右到左移动。我正在使用砖块图像的重复图案,使其看起来像整面墙都被砖块覆盖。

以下是创建和填充模式的相关代码:

this.update = function() {
    var context = gCanvas.context;
    context.fillStyle = context.createPattern(this.image, "repeat");
    context.fillRect(this.x, this.y, this.width, this.height);
};

墙从右向左移动,但图案不随之移动,使图案看起来像是静态图像,而墙在其上滚动。我需要的是让图案跟随墙壁,使其看起来就像整面墙壁从右向左移动。

请查看以下 jsfiddle 以了解其实际效果:

https://jsfiddle.net/ugmo1cd3/4/

【问题讨论】:

标签: javascript css html canvas


【解决方案1】:

您可以将墙更新功能更改为

this.update = function() {
    var context = gCanvas.context;
    context.fillStyle = context.createPattern(this.image, "repeat");
    context.save();
    context.translate(this.x, this.y);
    context.fillRect(0, 0, this.width, this.height);
    context.restore();
};

图案现在将从画布的 (x,y) 而不是 (0,0) 开始

【讨论】:

  • 你也可以将createPattern移动到构造函数中:this.PAT = gCanvas.context.createPattern(this.image, "repeat");,然后在更新函数中使用PAT,以便在每次更新时停止创建
  • 这正是我所需要的!赞成和接受的答案,但似乎还不够。谢谢!仅供参考 - 这是最后一点让我完成创建我的游戏 - chrome.google.com/webstore/detail/robotman/…。您现在可以感觉到自己参与其中。 :)
猜你喜欢
  • 2015-12-03
  • 1970-01-01
  • 2011-12-10
  • 1970-01-01
  • 2013-03-04
  • 2019-04-12
  • 1970-01-01
  • 1970-01-01
  • 2015-10-22
相关资源
最近更新 更多