【问题标题】:How does negative co-ordinate work in HTML5 canvas?负坐标在 HTML5 画布中如何工作?
【发布时间】:2013-07-23 18:52:15
【问题描述】:
function Background() {
    this.speed = 1; // Redefine speed of the background for panning

   // Implement abstract function
   this.draw = function() {
        // Pan background
        this.y += this.speed;
        this.context.drawImage(imageRepository.background, this.x, this.y);

        // Draw another image at the top edge of the first image
        this.context.drawImage(imageRepository.background, this.x, this.y - this.canvasHeight);

        // If the image scrolled off the screen, reset
        if (this.y >= this.canvasHeight)
            this.y = 0;
    };
}

我试图理解上面的代码,它给出了无限循环渲染背景图像的逻辑(给人一种连续平移的错觉)。

下面这行我看不懂:

 this.context.drawImage(imageRepository.background, this.x, this.y - this.canvasHeight);

显然 this.y - this.canvasHeight 永远不会 > 0。画布如何解释负 y 坐标?或者简单地说,下面的代码会做什么?

ctx.drawImage(img, 0, -10);

【问题讨论】:

  • 它根据原点从 -10 开始绘制 y 位置。即:假设默认原点 0,0(左,上)离 y 轴 10 个像素不可见,或者您可以将其视为离屏幕 10 个像素的开始 y。
  • @dc5 +1 完全正确。此外,如果偏移量太大以至于无法在屏幕上绘制任何图像,则有证据表明某些浏览器根本不会费心渲染图像来获得性能。
  • 小心 drawImage 和负索引。我已经在这里深入介绍过:stackoverflow.com/questions/15328764/…

标签: javascript html html5-canvas


【解决方案1】:

它从 -10 开始绘制基于原点的 y 位置。

即:假设默认原点 0,0(左,上)离 y 轴 10 个像素不可见,或者您可以将其视为离屏幕 10 个像素的开始 y。

(将评论转换为答案)

【讨论】:

  • 用负坐标作为边距有什么办法让它可见?
  • @DanielKmak 听起来你的意思是把负数转换成正数,这样它就变成了边距? Math.abs(dx), Math.abs(dy)
猜你喜欢
  • 2011-10-15
  • 2014-08-27
  • 1970-01-01
  • 2015-04-18
  • 2013-01-02
  • 1970-01-01
  • 2020-05-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多