### Hatched Shapes Example Setup Source: https://github.com/golanlevin/p5.plotsvg/blob/main/examples/plotSvg_hatched_shapes/README.md Initializes the p5.js sketch, sets up the SVG export parameters, and creates an offscreen buffer for pixel analysis. Requires the p5.plotSvg library. ```javascript // plotSvg_hatched_shapes Hatched Shapes Example // Requires https://cdn.jsdelivr.net/npm/p5.plotsvg@latest/lib/p5.plotSvg.js // Golan Levin, December 2024 // // This sketch presents a hack for hatching SVG shapes. // Note: This method uses pixel analysis and is resolution-dependent. // // Click mouse or press ' ' to get a new composition // Press 'd' to toggle debug view. // Press 's' to export SVG. let bDoExportSvg = false; let bShowDebug = false; let HATCH_INTERVAL = 3; // the hatch spacing. Must be an integer. let HATCH_ANGLE = 0; let W, H; let shapes = []; let hatchBuffer; let hatchLines; let exportCount = 0; p5.disableFriendlyErrors = true; //====================================== function setup() { createCanvas(6 * 96, 4 * 96); // Postcard, 6"x4" @96dpi W = width; H = height; hatchBuffer = createGraphics(W*2, H*2, P2D); hatchBuffer.pixelDensity(1); hatchLines = []; makeThreeNewShapes(); // Set values for our SVG export: setSvgCoordinatePrecision(4); setSvgIndent(SVG_INDENT_SPACES, 2); setSvgDefaultStrokeColor('black'); setSvgDefaultStrokeWeight(1); } //====================================== function makeFilledShape() { // Note: shapes must not overlap edge of canvas // or else significant extra effort must be made. let pointsX = []; let pointsY = []; let nPts = int(round(random(5, 8))); let cx = random(0.25, 0.75) * W; let cy = random(0.25, 0.75) * H; for (let i = 0; i < nPts; i++) { let t = map(i, 0, nPts, 0, TWO_PI); let rx = random(0.10, 0.25) * W; let ry = random(0.10, 0.25) * H; let px = cx + rx * cos(t); let py = cy + ry * sin(t); pointsX[i] = px; pointsY[i] = py; } shapes.push([pointsX, pointsY]); } //====================================== function makeThreeNewShapes(){ shapes = []; makeFilledShape(); makeFilledShape(); makeFilledShape(); } //====================================== function draw() { background(245); if (bDoExportSvg) { let svgFilename = "plotSvg_hatched_shapes" + nf(exportCount,3) + ".svg"; beginRecordSvg(this, svgFilename); exportCount++; } stroke(0); drawShapeOutlines(); drawShapeHatchlines(); if (bDoExportSvg) { endRecordSvg(); bDoExportSvg = false; } } //====================================== function drawShapeOutlines(){ for (let s = 0; s < shapes.length; s++) { let pointsX = shapes[s][0]; let pointsY = shapes[s][1]; noFill(); stroke(0); beginShape(); for (let i = 0; i < pointsX.length; i++) { let px = pointsX[i]; let py = pointsY[i]; vertex(px, py); } endShape(CLOSE); } } //====================================== function drawShapeHatchlines(){ for (let s=0; s= 3) { hatchBuffer.background(0, 0, 0); hatchBuffer.fill(255); hatchBuffer.noStroke(); hatchBuffer.push(); ``` -------------------------------- ### Minimal p5.js Instance Mode Setup Source: https://github.com/golanlevin/p5.plotsvg/blob/main/examples/plotSvg_instancemode/README.md A basic p5.js sketch demonstrating instance mode with p5.plotSvg. Ensure p5.plotSvg is imported correctly for this setup. ```javascript import p5plot from 'p5.plotsvg'; function sketch(context) { context.setup = function() { context.createCanvas(400, 400); p5plot.beginRecordSvg(context, "output.svg"); context.circle(200, 200, 200); p5plot.endRecordSvg(); }; }; new p5(sketch, document.getElementById("container")); ``` -------------------------------- ### Full p5.plotSvg Sketch Example Source: https://context7.com/golanlevin/p5.plotsvg/llms.txt This sketch demonstrates comprehensive API usage for p5.plotSvg, including setup configurations, drawing primitives, curves, custom shapes, transformations, and text. Press 's' to export the drawing as an SVG file named 'full_example.svg'. Ensure p5.js and p5.plotSvg are included in your project. ```javascript // Full p5.plotSvg example — press 's' to save SVG p5.disableFriendlyErrors = true; let bDoExportSvg = false; function setup() { createCanvas(816, 1056); // 8.5 × 11 in at 96 dpi // Configure SVG output (call these once in setup) setSvgDocumentSize(816, 1056); setSvgResolutionDPI(96); setSvgDefaultStrokeColor('black'); setSvgDefaultStrokeWeight(1); setSvgCoordinatePrecision(4); setSvgTransformPrecision(6); setSvgIndent(SVG_INDENT_SPACES, 2); setSvgFlattenTransforms(false); setSvgMergeNamedGroups(true); setSvgInkscapeCompatibility(true); setSvgPointRadius(0.5); setSvgBackgroundColor('white'); } function keyPressed() { if (key === 's') bDoExportSvg = true; } function draw() { background(255); if (bDoExportSvg) { beginRecordSvg(this, "full_example.svg"); describe("Comprehensive p5.plotSvg demo sketch."); } // Group 1: Basic primitives beginSvgGroup("primitives"); stroke('black'); line(50, 50, 200, 50); rect(50, 80, 100, 60); circle(300, 110, 80); ellipse(450, 110, 120, 60); triangle(550, 80, 620, 160, 480, 160); quad(50, 200, 150, 180, 180, 240, 60, 260); point(250, 220); arc(380, 230, 100, 80, 0, PI, CHORD); endSvgGroup(); // Group 2: Curves beginSvgGroup("curves"); stroke('blue'); bezier(50, 320, 100, 270, 200, 370, 250, 320); curveTightness(0); curve(50, 380, 100, 360, 200, 400, 250, 380); endSvgGroup(); // Group 3: Custom shapes with vertex types beginSvgGroup("shapes"); stroke('red'); beginShape(); vertex(300, 300); bezierVertex(350, 270, 400, 330, 420, 300); vertex(420, 360); vertex(300, 360); endShape(CLOSE); stroke('green'); beginShape(); for (let i = 0; i < 16; i++) { let t = map(i, 0, 16, 0, TWO_PI); let r = (i % 2 === 0) ? 50 : 30; curveVertex(530 + r * cos(t), 330 + r * sin(t)); } endShape(CLOSE); endSvgGroup(); // Group 4: Transforms beginSvgGroup("transforms"); stroke('black'); push(); translate(150, 500); rotate(PI / 6); rect(-40, -25, 80, 50); pop(); push(); translate(300, 500); scale(1.5, 0.7); circle(0, 0, 80); pop(); push(); translate(450, 500); shearX(PI / 8); rect(-40, -25, 80, 50); pop(); endSvgGroup(); // Group 5: Text beginSvgGroup("text"); stroke('black'); textSize(32); textFont("Arial"); textAlign(LEFT, BASELINE); text("p5.plotSvg demo", 50, 700); endSvgGroup(); if (bDoExportSvg) { endRecordSvg(); // triggers download of "full_example.svg" bDoExportSvg = false; } } ``` -------------------------------- ### Start and End SVG Recording (Global Mode) Source: https://context7.com/golanlevin/p5.plotsvg/llms.txt Use beginRecordSvg() and endRecordSvg() to bracket drawing commands for SVG export. This example shows global mode usage, saving to 'mySketch.svg' by default. Press 's' to trigger the export. ```javascript p5.disableFriendlyErrors = true; let bDoExportSvg = false; function setup() { createCanvas(816, 1056); // 8.5×11 in at 96 dpi } function keyPressed() { if (key === 's') bDoExportSvg = true; } function draw() { background(255); if (bDoExportSvg) { beginRecordSvg(this, "mySketch.svg"); // saves "mySketch.svg" on export } line(0, 0, mouseX, mouseY); ellipse(width / 2, height / 2, 200, 200); if (bDoExportSvg) { endRecordSvg(); // triggers download of "mySketch.svg" bDoExportSvg = false; } } ``` -------------------------------- ### Start and End SVG Recording (Instance Mode) Source: https://context7.com/golanlevin/p5.plotsvg/llms.txt Instance mode usage of p5.plotSvg. The sketch is encapsulated within a function, and p5.plotSvg methods are called on the p5 instance. ```javascript import p5plot from 'p5.plotsvg'; function sketch(p) { p.setup = () => { p.createCanvas(400, 400); p5plot.beginRecordSvg(p, "output.svg"); p.circle(200, 200, 200); p5plot.endRecordSvg(); }; } new p5(sketch, document.getElementById("container")); ``` -------------------------------- ### beginSvgGroup Source: https://github.com/golanlevin/p5.plotsvg/blob/main/documentation.md Starts a new user-defined group for SVG elements. Optionally, you can assign a name to this group, which will be used as its ID. ```APIDOC ## beginSvgGroup ### Description Begins a new user-defined grouping of SVG elements. Optionally associates a group name to the SVG group. Be sure to call `endSvgGroup()` later or the SVG file will report errors. ### Parameters #### Path Parameters - `gname` (string) - Optional - Optional group name used as an ID for the SVG group. ``` -------------------------------- ### Elaborated p5.js Instance Mode with SVG Export Source: https://github.com/golanlevin/p5.plotsvg/blob/main/examples/plotSvg_instancemode/README.md An advanced p5.js sketch using instance mode to generate a squircle pattern and export it as an SVG. This example includes buttons for regeneration and SVG export. ```javascript // plotSvg_instancemode example // (squircle for plotters) // by lionel ringenbach - @ucodia // 26.02.2025 function squircle(sketch) { let exportSvg = false; let seed = 12345; let regenerateButton; let exportSvgButton; sketch.setup = function () { sketch.createCanvas(576, 576); // 6"x6" at 96 dpi regenerateButton = sketch.createButton("Regenerate"); regenerateButton.position(0, sketch.height); regenerateButton.mousePressed(regenerate); exportSvgButton = sketch.createButton("Export SVG"); exportSvgButton.position(100, sketch.height); exportSvgButton.mousePressed(initiateSvgExport); }; function regenerate() { seed = sketch.round(sketch.millis()); } function initiateSvgExport() { exportSvg = true; } sketch.draw = function () { sketch.rectMode(sketch.CENTER); sketch.randomSeed(seed); sketch.background(255); sketch.strokeWeight(1); sketch.stroke(0); sketch.noFill(); if (exportSvg) { beginRecordSvg(sketch, "plotSvg_instancemode_" + seed + ".svg"); } // pick random line number and rotation increment let nLines = sketch.random(10, 100); let rotInc = sketch.random() < 0.5 ? sketch.random(-0.1, 0.1) : 0; let maxW = sketch.width * 0.75; let minW = sketch.width * 0.01; let wInc = (maxW - minW) / nLines; for (let i = 0; i < nLines; i++) { let rot = rotInc * i; let r = sketch.map(i, 0, nLines - 1, 0, sketch.width * 0.1); let w = maxW - i * wInc; sketch.push(); sketch.translate(sketch.width / 2, sketch.height / 2); sketch.rotate(rot); sketch.translate(-sketch.width / 2, -sketch.height / 2); sketch.rect(sketch.width / 2, sketch.height / 2, w, w, r); sketch.pop(); } if (exportSvg) { endRecordSvg(); exportSvg = false; } }; } new p5(squircle); ``` -------------------------------- ### Capture SVG String and Log Length Source: https://context7.com/golanlevin/p5.plotsvg/llms.txt This example demonstrates how to capture the generated SVG content as a string using endRecordSvg() and log its length. Ensure beginRecordSvg() is called prior to this. ```javascript function draw() { background(255); if (bDoExportSvg) { beginRecordSvg(this, "art.svg"); } for (let i = 0; i < 20; i++) { stroke(random(255), random(255), random(255)); line(random(width), random(height), random(width), random(height)); } if (bDoExportSvg) { let svgString = endRecordSvg(); // returns full SVG text console.log("SVG length:", svgString.length); bDoExportSvg = false; } } ``` -------------------------------- ### Static SVG Export with p5.plotSvg Source: https://github.com/golanlevin/p5.plotsvg/blob/main/examples/plotSvg_hello_static/README.md Use this snippet for basic SVG generation in static mode. Ensure p5.plotSvg is included. The SVG is exported automatically at the end of setup(). ```javascript // plotSvg_hello_static Example // Extremely simple demo of using p5.plotSvg to export SVG files. // Requires https://cdn.jsdelivr.net/npm/p5.plotsvg@latest/lib/p5.plotSvg.js // // Note 1: This sketch will export an SVG at the very moment when you run it. // Note 2: This sketch issues many warnings; the following line quiets them: p5.disableFriendlyErrors = true; function setup() { createCanvas(576, 384); // Postcard size: 6"x4" at 96 dpi background(245); noFill(); beginRecordSvg(this, "plotSvg_hello_static.svg"); circle(width/2, height/2, 300); ellipse(width/2-60, height/2-40, 30, 50); ellipse(width/2+60, height/2-40, 30, 50); arc(width/2, height/2+30, 150, 100, 0, PI); endRecordSvg(); } ``` -------------------------------- ### p5.js Instance Mode Sketch with p5.plotSvg Source: https://github.com/golanlevin/p5.plotsvg/blob/main/README.md A minimal sketch.js file demonstrating how to use p5.plotSvg in p5.js instance mode. Ensure p5.js and p5.plotSvg are correctly imported and the sketch is initialized with a container element. ```javascript // This is a minimal sketch.js file for instance mode. import p5plot from 'p5.plotsvg'; function sketch(context) { context.setup = function() { context.createCanvas(400, 400); p5plot.beginRecordSvg(context, "output.svg"); context.circle(200, 200, 200); p5plot.endRecordSvg(); }; }; new p5(sketch, document.getElementById("container")); ``` -------------------------------- ### beginRecordSvg Source: https://github.com/golanlevin/p5.plotsvg/blob/main/documentation.md Begins recording SVG output for a p5.js sketch. Initializes recording state, validates and sets the output filename, and overrides p5.js drawing functions to capture drawing commands for SVG export. ```APIDOC ## beginRecordSvg ### Description Begins recording SVG output for a p5.js sketch. Initializes recording state, validates and sets the output filename, and overrides p5.js drawing functions to capture drawing commands for SVG export. ### Parameters * `p5Instance` **[object]** A reference to the current p5.js sketch (e.g. `this`). * `fn` **[string]?** Optional filename for the output SVG file. The *explicit* use of `null` will prevent a file from being saved. Behavior: * `beginRecordSvg(this, "file.svg"); // saves to "file.svg"` * `beginRecordSvg(this); // saves to "output.svg" (default)` * `beginRecordSvg(this, null); // DOES NOT save any file!` ``` -------------------------------- ### Initialize SVG Recording in p5.plotSvg Source: https://github.com/golanlevin/p5.plotsvg/blob/main/CONTEXT.md Demonstrates various ways to begin recording SVG output. Choose the form that best suits your sketch's mode (legacy, global, or instance). The namespace form with a null filename is useful for programmatic SVG generation without immediate download. ```javascript beginRecordSvg(this, "file.svg"); // legacy explicit p5 instance form beginRecordSvg("file.svg"); // global-mode add-on style sketch.beginRecordSvg("file.svg"); // instance-mode add-on style p5plotSvg.beginRecordSvg(this, null); // namespace form, no download ``` -------------------------------- ### Get Default Stroke Color Source: https://context7.com/golanlevin/p5.plotsvg/llms.txt Returns the current default stroke color string. Useful for resetting stroke color back to the default after drawing colored elements. ```javascript function setup() { createCanvas(600, 600); setSvgDefaultStrokeColor('black'); } function draw() { if (bDoExportSvg) beginRecordSvg(this, "reset_color.svg"); stroke('red'); circle(100, 100, 80); stroke(getDefaultStrokeColor()); // reset to 'black' rect(200, 200, 100, 100); if (bDoExportSvg) { endRecordSvg(); bDoExportSvg = false; } } ``` -------------------------------- ### Build p5.plotSvg Project Source: https://github.com/golanlevin/p5.plotsvg/blob/main/CONTEXT.md Run this command to build the project. It generates JavaScript files for browser script loading and ESM import. ```sh npm run build ``` -------------------------------- ### Define p5.js v1 Compatibility Flags Source: https://github.com/golanlevin/p5.plotsvg/blob/main/test/compat2/runner-v1.html Sets global flags to indicate compatibility with p5.js v1 and specifies the instance probe file for v1 compatibility. ```javascript window.P5_COMPAT2_MAJOR = 1; window.P5_COMPAT2_INSTANCE_PROBE = "instance-probe-v1.html"; ``` -------------------------------- ### Build and Run Add-on Build Baseline Test Source: https://github.com/golanlevin/p5.plotsvg/blob/main/test/README.md Build the add-on using 'npm run build' and then execute the Playwright test for the add-on build baseline. This verifies the generated files in the 'dist/' directory for both classic script and ES module loading. ```sh npm run build npx playwright test test/p5-addon-build.spec.js --browser=chromium ``` -------------------------------- ### Pause and Resume SVG Recording Source: https://context7.com/golanlevin/p5.plotsvg/llms.txt Use pauseRecordSvg() to temporarily exclude drawing commands from the SVG output. Call with `true` to pause and `false` to resume. This is useful for suppressing non-plottable elements like backgrounds or guides. ```javascript function draw() { background(240); // do NOT export background if (bDoExportSvg) { beginRecordSvg(this, "design.svg"); } // Draw guide marks on screen only – pause recording pauseRecordSvg(true); stroke(200); line(0, height / 2, width, height / 2); // horizontal guide – not exported pauseRecordSvg(false); // Real plotter paths resume here stroke('black'); ellipse(width / 2, height / 2, 300, 300); if (bDoExportSvg) { endRecordSvg(); bDoExportSvg = false; } } ``` -------------------------------- ### Utility Functions Source: https://github.com/golanlevin/p5.plotsvg/blob/main/CONTEXT.md Utility functions for retrieving default settings and checking recording status. ```APIDOC ## getDefaultStrokeColor ### Description Retrieves the current default stroke color. ### Method `getDefaultStrokeColor()` ## isRecordingSVG ### Description Checks if SVG recording is currently active. ### Method `isRecordingSVG()` ``` -------------------------------- ### Run All Playwright Tests Source: https://github.com/golanlevin/p5.plotsvg/blob/main/CONTEXT.md Execute the main test command to run the browser-based test suite using Playwright. ```sh npm test ``` -------------------------------- ### Include p5.plotSvg.js in HTML Source: https://github.com/golanlevin/p5.plotsvg/blob/main/README.md Include the p5.js and p5.plotSvg.js libraries in your project's index.html file. The sketch.js file should be linked after these libraries. ```html ``` -------------------------------- ### beginSvgGroup Source: https://github.com/golanlevin/p5.plotsvg/blob/main/documentation.md Begins a new SVG group. All subsequent drawing commands will be enclosed within this group until `endSvgGroup()` is called. ```APIDOC ## beginSvgGroup ### Description Begins a new SVG group. All subsequent drawing commands will be enclosed within this group until `endSvgGroup()` is called. ### Parameters * `groupName` **[string]?** Optional name for the SVG group. This name can be used for styling or identification purposes. ``` -------------------------------- ### p5.plotSvg Recording Flow Source: https://github.com/golanlevin/p5.plotsvg/blob/main/CONTEXT.md Illustrates the sequence of operations for recording p5.js drawing commands and exporting them as an SVG string. This process involves overriding p5 functions, capturing commands, and then restoring the original functions. ```text beginRecordSvg() -> detect p5 v1/v2 and global/instance mode -> override p5 drawing functions with descriptor-safe wrappers -> drawing calls append command objects to session.commands endRecordSvg() -> exportSVG() serializes command objects -> postProcessSvgString() applies optional SVG post-processors -> restoreP5Functions() restores exact original descriptors -> return SVG string ``` -------------------------------- ### Run Automated Compatibility Audit Source: https://github.com/golanlevin/p5.plotsvg/blob/main/test/README.md Execute the automated compatibility audit using Playwright. This test specifically checks for known gaps in compatibility between p5.js versions and should be updated as issues are resolved. ```sh npx playwright test test/p5-compat2.spec.js --browser=chromium ``` -------------------------------- ### Run Prototype API Baseline Test Source: https://github.com/golanlevin/p5.plotsvg/blob/main/test/README.md Execute the Playwright test for the prototype API baseline. This test verifies add-on style prototype methods and existing entry points in both p5 v1 and p5 v2, including different argument forms. ```sh npx playwright test test/p5-prototype-api.spec.js --browser=chromium ``` -------------------------------- ### Run Playwright Tests for p5.plotSvg Source: https://github.com/golanlevin/p5.plotsvg/blob/main/TEMP_DEBUG_SUMMARY.md Execute Playwright tests for various p5.plotSvg build configurations and APIs. Ensure tests are run against Chromium browser. ```sh npm run build npx playwright test test/p5-addon-build.spec.js test/p5-prototype-api.spec.js test/p5-smorgasbord.spec.js --browser=chromium ``` -------------------------------- ### p5.js Drawing Recorder and SVG Exporter Source: https://github.com/golanlevin/p5.plotsvg/blob/main/examples/plotSvg_drawing_recorder/README.md This sketch records user drawings and exports them as an SVG file. It uses the p5.plotSvg library for SVG generation. The sketch is mobile-friendly and includes buttons for exporting and clearing. ```javascript // This sketch records a series of marks drawn by the user // and exports an SVG file when the 'Export SVG' button is pressed. // This sketch is mobile-friendly. // // Uses https://github.com/golanlevin/p5.plotSvg (v.0.1.x) // A Plotter-Oriented SVG Exporter for p5.js // Golan Levin, November 2024 p5.disableFriendlyErrors = true; let exportSvgButton; let clearButton; let bDoExportSvg = false; let marks = []; let currentMark = []; function setup() { createCanvas(375, 500); // phone-safe size exportSvgButton = createButton('Export SVG'); exportSvgButton.position(10, 10); exportSvgButton.mousePressed(() => bDoExportSvg = true); clearButton = createButton('Clear'); clearButton.position(100, 10); clearButton.mousePressed(() => { marks = []; currentMark = []; }); } //------------------------------------- function keyPressed(){ if (key == 's'){ // Another way to initiate SVG exporting bDoExportSvg = true; } else if (key == ' '){ // Clear recordings with spacebar marks = []; currentMark = []; } } //------------------------------------- function mousePressed(){ currentMark = []; currentMark.push(createVector(mouseX, mouseY)); } function mouseDragged(){ currentMark.push(createVector(mouseX, mouseY)); } function mouseReleased(){ if (currentMark){ marks.push(currentMark); } } function touchStarted(event) { if (event.target.tagName === 'CANVAS') { mousePressed(); return false; } } function touchMoved(event) { if (event.target.tagName === 'CANVAS') { mouseDragged(); return false; } } function touchEnded(event) { if (event.target.tagName === 'CANVAS') { mouseReleased(); return false; } } //------------------------------------- function draw(){ background(245); strokeWeight(1); stroke(0); noFill(); if (bDoExportSvg){ let svgFilename = "plotSvg_recording_" + frameCount; beginRecordSvg(this, svgFilename + ".svg"); } // Draw each of the stored marks for (let j=0; j` and `` elements (produced by `beginShape()`/`endShape()`) to be output as `` elements instead. Useful for downstream tools that require `` elements. ```javascript function setup() { createCanvas(600, 600); setSvgExportPolylinesAsPaths(true); // all polylines become } ``` -------------------------------- ### Export Polylines as Paths Source: https://github.com/golanlevin/p5.plotsvg/blob/main/README.md Use `setSvgExportPolylinesAsPaths()` to control whether polylines are exported as `` elements or converted to `` elements. This is an experimental feature for downstream tool compatibility. ```javascript setSvgExportPolylinesAsPaths() ``` -------------------------------- ### Run Specific Playwright Test Source: https://github.com/golanlevin/p5.plotsvg/blob/main/CONTEXT.md Use these commands to run focused Playwright tests on specific files or configurations. Specify the browser for testing. ```sh npx playwright test test/p5-compat.spec.js --browser=chromium ``` ```sh npx playwright test test/p5-compat2.spec.js --browser=chromium ``` ```sh npx playwright test test/p5-prototype-api.spec.js --browser=chromium ``` ```sh npx playwright test test/p5-addon-build.spec.js --browser=chromium ``` ```sh npx playwright test test/p5-smorgasbord.spec.js --browser=chromium ``` ```sh npx playwright test test/p5-path-regression.spec.js --browser=chromium ``` ```sh npx playwright test test/p5-svg-escaping.spec.js --browser=chromium ``` -------------------------------- ### Generate Hatched Shapes in p5.js Source: https://github.com/golanlevin/p5.plotsvg/blob/main/examples/plotSvg_hatched_shapes/README.md This code generates hatched shapes. It first draws a shape onto a buffer, then processes the buffer to find hatch lines, and finally transforms these lines back to the original coordinate system. ```javascript hatchBuffer.translate(cx, cy); hatchBuffer.rotate(HATCH_ANGLE); hatchBuffer.translate(-cx, -cy); hatchBuffer.push(); hatchBuffer.translate(W/2, H/2); hatchBuffer.beginShape(); for (let i=0; i= 128 && prevR < 128) { hatchLines.push(createVector(x + 1, y)); // line start bActive = true; } else if (currR < 128 && prevR >= 128 && bActive) { hatchLines.push(createVector(x - 1, y)); // line end bActive = false; } } prevR = currR; } } // 3. Un-rotate the hatch lines. for (let i = 0; i < hatchLines.length; i += 2) { let st = hatchLines[i]; // start let en = hatchLines[i+1]; // end let sxo = st.x - cx; let syo = st.y - cy; let sxr = sxo * Math.cos(-HATCH_ANGLE) - syo * Math.sin(-HATCH_ANGLE) + cx; let syr = syo * Math.cos(-HATCH_ANGLE) + sxo * Math.sin(-HATCH_ANGLE) + cy; let exo = en.x - cx; let eyo = en.y - cy; let exr = exo * Math.cos(-HATCH_ANGLE) - eyo * Math.sin(-HATCH_ANGLE) + cx; let eyr = eyo * Math.cos(-HATCH_ANGLE) + exo * Math.sin(-HATCH_ANGLE) + cy; hatchLines[i].set(sxr, syr); hatchLines[i+1].set(exr, eyr); } for (let i = 0; i < hatchLines.length; i++) { let px = hatchLines[i].x - W/2; let py = hatchLines[i].y - H/2; hatchLines[i].set(px, py); } } ``` -------------------------------- ### Run Smorgasbord Baseline Test Source: https://github.com/golanlevin/p5.plotsvg/blob/main/test/README.md Execute the Playwright test for the Smorgasbord baseline. This test compares SVG output from p5 v1 and p5 v2 sketches to ensure validity, non-emptiness, and coverage of expected SVG element types. ```sh npx playwright test test/p5-smorgasbord.spec.js --browser=chromium ``` -------------------------------- ### SVG Recording Functions Source: https://github.com/golanlevin/p5.plotsvg/blob/main/CONTEXT.md Functions to begin, pause, and end the recording of SVG output. ```APIDOC ## beginRecordSvg ### Description Starts the recording of SVG output. Can be called in several ways depending on the p5 instance mode. ### Method `beginRecordSvg(this, "file.svg");` // legacy explicit p5 instance form `beginRecordSvg("file.svg");` // global-mode add-on style `sketch.beginRecordSvg("file.svg");` // instance-mode add-on style `p5plotSvg.beginRecordSvg(this, null);` // namespace form, no download ## pauseRecordSvg ### Description Pauses or resumes the recording of SVG output. ### Method `pauseRecordSvg(bPause)` ## endRecordSvg ### Description Ends the recording of SVG output and finalizes the SVG document. ### Method `endRecordSvg()` ``` -------------------------------- ### setSvgResolutionDPCM Source: https://context7.com/golanlevin/p5.plotsvg/llms.txt Sets the DPI in dots-per-centimeter instead of dots-per-inch. Switches unit output to `cm`. Equivalent default is ~37.795 dpcm (96 dpi). ```APIDOC ## setSvgResolutionDPCM ### Description Sets the DPI in dots-per-centimeter instead of dots-per-inch. Switches unit output to `cm`. Equivalent default is ~37.795 dpcm (96 dpi). ### Parameters #### Path Parameters - **dpcm** (number) - The resolution in dots per centimeter. ### Request Example ```js function setup() { createCanvas(794, 1123); // A4 at ~96 dpi setSvgResolutionDPCM(37.7953); // output in centimeters: 21 × 29.7 cm } ``` ``` -------------------------------- ### setSvgIndent Source: https://github.com/golanlevin/p5.plotsvg/blob/main/documentation.md Configures the indentation for SVG output, allowing for spaces, tabs, or no indentation. You can specify the type and amount of indentation. ```APIDOC ## setSvgIndent ### Description Sets the type and amount of indentation used for formatting SVG output. The function allows for spaces, tabs, or no indentation. ### Parameters #### Path Parameters - `itype` (string) - Required - The type of indentation to use. Valid values are 'SVG_INDENT_SPACES', 'SVG_INDENT_TABS', or 'SVG_INDENT_NONE'. - `inum` (number) - Optional - Number of spaces or tabs to use for indentation. Must be a non-negative integer if provided. Defaults to 2 for spaces and 1 for tabs. ``` -------------------------------- ### Run Automated Browser Smoke Test Source: https://github.com/golanlevin/p5.plotsvg/blob/main/test/README.md Execute the automated browser smoke test using Playwright to verify compatibility between different p5.js versions. This test ensures expected geometry output without undefined or NaN values. ```sh npx playwright test test/p5-compat.spec.js --browser=chromium ``` -------------------------------- ### Animating SVG Export with p5.js Source: https://github.com/golanlevin/p5.plotsvg/blob/main/examples/plotSvg_hello_animating/README.md This sketch uses p5.js's animation mode to draw and export an SVG file. Press the 's' key to initiate the SVG export. The `p5.disableFriendlyErrors = true;` line is used to suppress common warnings. ```javascript // plotSvg_hello_animating Example // This sketch demonstrates how to use the p5.plotSvg library // to export SVG files during interaction. Press 's' to export an SVG. // This line of code disables the p5.js "Friendly Error System" (FES), // in order to prevent several distracting warnings: p5.disableFriendlyErrors = true; let bDoExportSvg = false; function setup() { // Postcard size: 6"x4" at 96 dpi createCanvas(576, 384); } function keyPressed(){ if (key == 's'){ // Initiate SVG exporting bDoExportSvg = true; } } function draw(){ background(245); strokeWeight(1); stroke(0); noFill(); if (bDoExportSvg){ // Begin exporting, if requested beginRecordSvg(this, "plotSvg_hello_animating.svg"); } // Draw your artwork here. push(); translate(width/2, height/2); beginShape(); for (let i=0; i<=400; i++){ let val = noise(i/100 + millis()/1000) - 0.5; vertex(i-200, 200*val); } endShape(); rectMode(CENTER); rect(0,0, 400,300); pop(); if (bDoExportSvg){ // End exporting, if doing so endRecordSvg(); bDoExportSvg = false; } } ``` -------------------------------- ### Export SVG with p5.js Source: https://github.com/golanlevin/p5.plotsvg/blob/main/README.md This sketch uses p5.js to draw on a canvas and allows exporting the drawing as an SVG file by pressing the 's' key. Ensure p5.js is included in your HTML. The canvas dimensions are set to 8.5"x11" at 96 dpi. ```javascript // This is the sketch.js file. // Press 's' to export the SVG. // Note that p5.js is used in 'global mode'. p5.disableFriendlyErrors = true; // keep warnings quiet let bDoExportSvg = false; function setup(){ // These canvas dimensions are 8.5"x11" at 96 dpi createCanvas(816, 1056); } function keyPressed(){ if (key == 's'){ bDoExportSvg = true; } } function draw(){ background(255); if (bDoExportSvg){ beginRecordSvg(this, "myOutput.svg"); } // Draw stuff here, such as: line(0,0, mouseX, mouseY); if (bDoExportSvg){ endRecordSvg(); bDoExportSvg = false; } } ``` -------------------------------- ### setSvgIndent Source: https://github.com/golanlevin/p5.plotsvg/blob/main/documentation.md Sets the indentation string for the SVG output. This is useful for pretty-printing the SVG file. ```APIDOC ## setSvgIndent ### Description Sets the indentation string for the SVG output. This is useful for pretty-printing the SVG file. ### Parameters * `indent` **[string]** The string to use for indentation. For example, `" "` for two spaces or `"\t"` for a tab. ``` -------------------------------- ### Run Path Data Regression Baseline Test Source: https://github.com/golanlevin/p5.plotsvg/blob/main/test/README.md Execute the Playwright test for the path data regression baseline. This test verifies exact exported 'points' and 'd' strings for various p5.js vertex shapes and path types in p5 v1. ```sh npx playwright test test/p5-path-regression.spec.js --browser=chromium ```