Izhaki
Izhaki

Reputation: 23586

HTML5 Canvas - what happens when clip(), translate() and scale() are called consecutively?

How does the HTML5 canvas behave when one makes consecutive calls to clip(), translate() or scale()?

Upvotes: 1

Views: 504

Answers (1)

Izhaki
Izhaki

Reputation: 23586

Clip()

Many paths before calling clip()

If one draws more than one path between calling beginPath() and clip(), all the paths serve as separate clip regions.

So with this code (jsfiddle):

// Clip
iContext.beginPath(); 
iContext.rect( 10, 10, 10, 10 );
iContext.rect( 30, 30, 10, 10 );
iContext.clip();

// Draw rect
iContext.beginPath();
iContext.rect( 0, 0, 100, 100 );
iContext.fill();

The result will be:

Two squares

Calling clip() many times

When calling clip() more than once (without calling save() and restore() between the calls, the resultant clip area is an intersection of all the clipping paths.

So this code (jsfiddle):

// First Clip
iContext.beginPath();
iContext.rect( 10, 10, 30, 30 );
iContext.clip();

// Second Clip
iContext.beginPath();
iContext.rect( 30, 30, 30, 30 );
iContext.clip();

// Draw rect
iContext.beginPath();
iContext.rect( 0, 0, 100, 100 );
iContext.fill();

Will result in this intersected clip region:

One square, which is an intersection of the two rectangles in the code

Translate

Translate is cumulative.

So calling a translate( 10, 10 ), followed by translate( 30, 30 ) will give an overall translation of ( 40, 40 ).

So calling this code (jsfiddle):

// First Clip
iContext.translate( 10, 10 );
iContext.translate( 30, 30 );

// Draw rect
iContext.beginPath();
iContext.rect( 0, 0, 10, 10 );
iContext.fill();

will draw:

A rect at 40, 40 - the sum of the two translation figures

Scale()

Scale is cumulative.

So calling scale( 2, 2 ) twice, will give an overall scale of (4, 4).

This code (jsfiddle):

// First Clip
iContext.scale( 2, 2 );
iContext.scale( 2, 2 );

// Draw rect
iContext.beginPath();
iContext.rect( 0, 0, 10, 10 );
iContext.fill();

Will draw this:

A square at 0,0 with dimensions 40,40 - the original 10,10 size was multiplied twice

Upvotes: 5

Related Questions