diff --git a/src/core/transform.js b/src/core/transform.js index 2c802d3f69..1cccf25815 100644 --- a/src/core/transform.js +++ b/src/core/transform.js @@ -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 + *
+ * + * 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); + * } + * + *
+ */ + 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; diff --git a/test/unit/visual/cases/transform.js b/test/unit/visual/cases/transform.js new file mode 100644 index 0000000000..10f449b891 --- /dev/null +++ b/test/unit/visual/cases/transform.js @@ -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(); +}); \ No newline at end of file