Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does negative co-ordinate work in HTML5 canvas?

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;
    };
}

I was trying to understand the above code which gives the logic of rendering a background image in infinite loop(giving an illusion of continuous panning).

I could not understand the following line:

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

Clearly this.y - this.canvasHeight will never be > 0. How is the negative y co-ordinate interpreted by the canvas? Or put simply, what will the following code do?

ctx.drawImage(img, 0, -10);
like image 450
Bhavish Agarwal Avatar asked Jul 23 '13 18:07

Bhavish Agarwal


1 Answers

It draws starting at -10 for the y position based on the origin.

i.e.: Assuming the default origin of 0,0 (left, top) 10 pixels off the y-axis will not be visible or you could think of it as start y at 10 pixels off screen.

(Converting comment to answer)

like image 60
dc5 Avatar answered Sep 28 '22 07:09

dc5