Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions src/core/transform.js
Original file line number Diff line number Diff line change
Expand Up @@ -1962,6 +1962,43 @@ function transform(p5, fn){
fn.pop = function() {
this._renderer.pop();
};
/**
* Sets the coordinate system to a new viewport.
*
* Calling `setViewport(xmin, xmax, ymin, ymax)` remaps the canvas's
* coordinate system. The top-left corner of the canvas will be `(xmin, ymin)`
* and the bottom-right corner will be `(xmax, ymax)`.
*
* @method setViewport
* @param {Number} xmin The minimum x-value of the viewport.
* @param {Number} xmax The maximum x-value of the viewport.
* @param {Number} ymin The minimum y-value of the viewport.
* @param {Number} ymax The maximum y-value of the viewport.
* @chainable
*
* @example
* <div>
* <code>
* function setup() {
* createCanvas(400, 400);
* setViewport(-200, 200, -200, 200);
* background(240);
* // Draw a horizontal line through the center
* line(-200, 0, 200, 0);
* // Draw a vertical line through the center
* line(0, -200, 0, 200);
* }
* </code>
* </div>
*/
fn.setViewport = function(xmin, xmax, ymin, ymax) {
this.resetMatrix();
const scaleX = this.width / (xmax - xmin);
const scaleY = this.height / (ymax - ymin);
this.scale(scaleX, scaleY);
this.translate(-xmin, -ymin);
return this;
};
}

export default transform;
Expand Down
11 changes: 11 additions & 0 deletions test/unit/visual/cases/transform.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { visualTest } from '../visualTest';

visualTest('setViewport remaps the coordinate system', function(p5, screenshot) {
p5.createCanvas(100, 100);
p5.setViewport(-50, 50, -50, 50);
p5.background(240);
p5.stroke(0);
p5.line(-50, 0, 50, 0);
p5.line(0, -50, 0, 50);
screenshot();
});
Loading