【发布时间】: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