Git Product home page Git Product logo

p5.bezier's Introduction

p5.bezier

cover

npm version GitHub license

p5.bezier is a p5.js library engineered to assist you in creating Bézier curves. It is an enhancement of the original p5.js bezier() function, extending its capabilities beyond the limitation of four control points.

Try it now on p5.js Web Editor!

While p5.bezier is designed to integrate with p5.js, it operates independently as well. It's necessary to initialize the library and specify the target canvas by invoking initBezier(canvas) at the start of your code.

To draw a Bézier curve on canvas, you can simply use newBezier():

newBezier([
  [85, 20],
  [10, 10],
  [90, 90],
  [15, 80],
  [20, 100],
])

What is a Bézier Curve?

A Bézier curve is a type of curve that's widely used in computer graphics, design, etc. It was named after Pierre Bézier who employed it in car design during the 1960s. Due to its smooth and continuous nature, it's ideal for creating visually pleasing shapes and textures in various design fields.

Getting Started

To use the p5.bezier library, first download the p5.bezier.min.js file and place it in your project directory. Then, include the following line in your HTML file:

<script src="p5.bezier.min.js"></script>

Alternatively, you can use the library through a content delivery network (CDN):

<script src="https://cdn.jsdelivr.net/npm/p5bezier@latest"></script>

Once included, the entire library is encapsulated within the p5bezier object. To call the functions provided by the library, prepend p5bezier to the function name:

p5bezier.initBezier(c)

NPM

You can also install the library using the package manager NPM (recommended):

npm install p5bezier

Then, import the modules into your project:

import { initBezier, newBezier, newBezierObject } from 'p5bezier'

Init for Bézier

You must initialize the Bézier drawing system with the canvas you are drawing on. Here's an example with p5.js:

function setup() {
  let c = createCanvas(100, 100)
+ initBezier(c)
}

Draw a Bézier Curve

The simplest way to use the library is to call newBezier() in your draw() function. You can adjust the curve's style using fill() or strokeWeight() just like other shapes.

newBezier(pointsArray [, closeType] [, accuracy]);

pointsArray

This is an array of [x, y] pairs, each representing a control point for the curve. For example, [[10, 30], [5, 100], [25, 60]].

closeType (Optional)

This is a string, either "OPEN" or "CLOSE". Use "CLOSE" to automatically close the curve. The default is "OPEN".

accuracy (Optional)

This is an integer between 0 and 10, with a default value of 7. This value determines the accuracy of the Bézier curve. Higher values mean more vertices are used, leading to a more accurate curve, but at the cost of additional computation.

Create a Bézier Object

For advanced operations, such as computing the shortest distance from a point to the curve, use the newBezierObj() function. This method can also potentially optimize computation resources if placed within the setup() function, as vertices are calculated only once and can then be reused.

The usage of newBezierObj() is similar to newBezier(), but it returns a Bézier Curve Object that can be stored in a variable:

let bezierObject = newBezierObj(pointsArray [, closeType] [, accuracy]);

The call of newBezierObj will not draw the curve on canvas automatically. To draw the curve, use .draw() as one of many functions listed below:

  • .draw([dash])

    Renders the curve on the canvas.

    dash (Optional)

    Accepts an array of two numbers specifying the length of solid and broken sections of a dashed Bézier curve. For example, [10, 5] signifies a solid segment of 10px followed by a 5px break.

  • .update(newPointsArray)

    Updates the positions of control points. The number of control points should remain consistent with the initial curve configuration.

  • .move(x, y [, z, toDraw, dash])

    Translates the entire curve. This function does not modify the original object but instead generates and returns a new one. Hence, if you wish to update the curve using this method (which is faster than .update()), you may:

    bezierObject = bezierObject.move(6, 17, -22, false)

    By default, toDraw is set to true. However, if you wish to only update the curve without drawing it, you can set this parameter to false.

  • .shortest(pointX, pointY [, pointZ])

    Requires the x and y coordinates of an external point as input. It returns an array containing the coordinates of the nearest point on the curve. For instance, to draw a line between these two points:

    pointOnCurve = bezierObject.shortest(pointX, pointY)
    line(pointX, pointY, pointOnCurve[0], pointOnCurve[1])

Examples

cover

To execute the examples locally, download the repository to your local machine. Then, navigate to the examples directory using your terminal. Execute the following command:

npm install
node server.js name_of_example

For instance, to run the basic example, simply enter node server.js basic. Then, open your web browser and navigate to localhost:8000.

Currently available examples:

  • basic draws a simple Bézier curve with 5 control points across the canvas.
  • basic_object create a simple Bézier object with 5 control points across the canvas.
  • control_points draws a curve and its control points, which can be dragged around.
  • accuracy showcases curves drawn with varying levels of accuracy.
  • shortest_point draws the shortest line from the mouse pointer to the curve.
  • animation draws animated Bézier curves.

More complex examples to be updated.

Projects and Demos

Share your ideas and projects using the library!

TODOs

  1. More examples.
  2. offset(), intersection(), and curvature()... functions for Bézier object.
  3. Draw B-Spline curves.

References

p5.bezier's People

Contributors

dependabot[bot] avatar peilingjiang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

p5.bezier's Issues

p5 is not defined

when I use import {...} from 'bezier' in vite
I have this problem. p5 is not defined.
I found your js file is not import p5.

Writing to a p5 off-screen renderer doesn't seem to work

I am trying to use your lib with p5 by using an off-screen renderer, but nothing shows.
Here is an example:

let renderer;

function setup() {
let c = createCanvas(500, 500);
renderer = createGraphics(500, 500); // off-screen renderer

// Init p5.bezier drawer with the off-screen renderer
p5bezier.initBezier(renderer);

// Set styles for the curve
renderer.noFill();
renderer.stroke('black');
renderer.strokeWeight(2);
}

function draw() {
background(235);

// Draw the curve
p5bezier.newBezier([
[10, 10],
[100, 700],
[500, -800],
[800, 1000],
[10, 300]
]);

// normal bezier function
renderer.bezier(10, 10, 20, 30, 50, 50, 100, 60);

image(renderer, 0, 0);
// now the canvas should display the curve made by p5bezier
}

node import/require

I get a ReferenceError: self is not defined
at Object. (.../node_modules/p5bezier/lib/p5.bezier.min.js:2:198)
when using require.

and SyntaxError: Cannot use import statement outside a module
when using import.

I can use all other modules by using require - example:
chroma = require('chroma-js');

I am receiving an error when i try to use the p5.bezier library in editor.

🌸 p5.js says:
[sketch.js, line 6] "newBezier" is not defined in the current scope. If you have defined it in your code, you should check its scope, spelling, and letter-casing (JavaScript is case-sensitive).

Even though this is my first time downloading a library and im new to p5js, i believe i did everything correct, downloaded the p5.bezier file added them into the editor and added the provided script into the html but still recieve the error above

Incorrect point count check in Update() in bezier Object

image

Your docs say that the new array of points must be the same length as when created. True, but there seems to be a typo in the if check code. Clearly the point count is the same. My code that prints to the console:

UpdatePoints(amps){

    var p = []

    for(let i = 0; i < this.curve.controlPoints.length; i++){
        p.push([this.curve.controlPoints[i][0], amps[i]*this.max_amp_px])
    }
    console.log('update points length: '+ p.length+' bezier points length: '+ this.curve.controlPoints.length)

    this.curve.update(p)
}

After looking in the p5.bezier.min.js, this is the problematic code:

update(t){if(t.length!==this.controlPoints)throw"The number of points changed. (Keep the point array length the same.)"

It is not actually checking if the lengths are the same. It should be:
update(t){if(t.length!==this.controlPoints.length)throw"The number of points changed. (Keep the point array length the same.)"

That fixes the error.
This error cost me about 1h of frustration, but this is overall a great lib, so i am not complaining.

Troubles in starting it up in chrome

p5.bezier.min.js:1 Uncaught (in promise) TypeError: Found non-callable @@iterator
at Module.a (p5.bezier.min.js:1)

Using Svelte framework, p5.min.js, and the web link download of the p5.bezier.js file because i couldnt use the downloadable file. Everything just like the basic example usage. Because when i just <script> add the local file, then it doesnt find the functions and cant use the import keyword since its not a module and require neither. If i do like in the examples with p5bezier.initBezier() then: Uncaught (in promise) ReferenceError: p5bezier is not defined. Basically couldnt use local file and the downloadable has some error i know nothing about.
Svelte here is just the basic boilerplate with some p5 drawing custom scripts imported as local files. So i dont think its doing anything destructive.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.