Giter VIP home page Giter VIP logo

q5.js's Introduction

q5.js implements all of p5's 2D drawing, math, and user input functionality.

It's a drop-in replacement that's performance optimized and 23x smaller than p5. q5 even has a few exclusive features: top-level global mode, HDR color support, namespace mode, and text image caching.

But q5 doesn't include any friendly error messages, so its mainly for people who are already familiar with p5.js or JS programming in general. If you're a beginner, stick with p5 while developing a sketch, then use q5 to share your work.

Usage

q5 should work with your existing p5.js sketches, no modifications required! If you have any problems though, please make an issue report.

Use q5.js in your own project by adding this line to your HTML file:

<script src="https://q5js.org/q5.js"></script>

q5 is also available on npm!

npm install q5

Or try out the q5.js template sketch for the online p5.js Web Editor.

Support this project 🤝

q5 is open source and multi-licensed. Anyone can use q5 for free under the terms of the AGPLv3. 🎉

But if you want to use q5 commercially in a closed source product or service, you must comply with the p5play Professional License, which is only available to current p5play GitHub Sponsors or Patreon members paying for the appropriate tier.

If you can't afford to pay, you can apply for the free p5play Novice License. See LICENSING.md for more info.

Using p5 Addon Libraries

q5.js is compatible with popular p5 addons and projects that use p5, such as p5play, because it aliases Q5 to p5.

To use addons, simply load them after q5.js:

<script src="q5.js"></script>
<!-- load p5 addons after q5 -->
<script src="https://p5play.org/v3/planck.min.js"></script>
<script src="https://p5play.org/v3/p5play.js"></script>

New Features: Top-Level Global Mode

q5.js includes some exclusive features that aren't available in p5.js. Using them is optional!

In p5, functions like rect can't be used on the file level. They must be called from within p5 functions like setup and draw.

In q5, existing p5 2D sketches don't require any modification. But if you initialize Q5 at the top of your sketch, the preload and setup functions become optional.

new Q5();

noStroke();
let c = color(0, 126, 255, 102);
fill(c);
rect(15, 15, 35, 70);

This is great because you don't have to declare variables on the file level and then define them in preload or setup. You can declare and define them at the same time!

new Q5();

let cow = loadImage('cow.png');

preload();

function setup() {
	image(cow, 0, 0);
}

Note that if you use loadImage on the file level, q5 will wait to run setup and draw until the image loads. Optionally if you forgo defining preload, you can run it to signify that the sketch can start once loading is complete. Otherwise q5 will auto-start the sketch after 32ms of delay, this ensures code after new Q5() is run before the sketch starts.

New Features: HDR Color Support

Most modern devices support the "display-p3" HDR color space. If a device doesn't support it, q5 will fall back to "srgb".

In q5, colorMode accepts 'rgb', 'srgb', and 'oklch'. The default mode is 'rgb', which upgrades rgb colors to HDR on supported displays. Specifying 'srgb' on an HDR capable device enables sRGB gamut correction for rgb colors.

The oklch color format is the best way to work with HDR colors!

https://evilmartians.com/chronicles/oklch-in-css-why-quit-rgb-hsl

colorMode('oklch');

//       (lightness, chroma, hue, alpha)
let c = color(0.637, 0.287, 16.57, 1);

The color function doesn't accept percentages so you'll have to convert those to decimal values. Also its string parsing capability is limited to simple named colors and the hex "#RRGGBB" or "#RRGGBBAA" formats.

Use new Color() to create color objects without any parsing overhead.

q5 also exposes color components as single letter properties of Color objects. For example, you can easily change the red of rgb colors like this c.r = 128 or the hue of oklch colors like this c.h = 180.

Support for the HSV color format was removed in q5 v1.9.3 because color experts thought HSV was flawed, outdated, and ought to be abandoned way back in 1997! oklch is superior in every way.

https://en.wikipedia.org/wiki/HSL_and_HSV#Disadvantages

New Features: Customize Canvas Context Attributes

In p5, you're stuck with the default canvas context attributes, which can't be changed. So the canvas must have an alpha layer, even if you don't need one. Also p5 doesn't support HDR color spaces or desynchronized rendering.

But q5 has its own defaults:

Q5.canvasOptions = {
	alpha: false,
	desynchronized: false,
	colorSpace: 'display-p3'
};

The Q5.canvasOptions object can be overridden, which will effect all q5 instances.You can also override any of these defaults by passing an options object as the fourth parameter to the createCanvas() function:

createCanvas(400, 400, '2d', {
	alpha: true
});

New Features: Namespace Mode

p5's instance mode enables multiple sketches to run on one page. To avoid needing to preface every p5 function with p. you can use a JS with statement.

let sketch = (p) => {
	with (p) {
		p.setup = () => {
			createCanvas(400, 400);
		};
		p.draw = () => {
			background(100);
		};
	}
};

let myp5 = new p5(sketch);

q5 introduces "namespace" mode, in addition to the global and instance modes. You can call the namespace variable whatever you like.

let q = new Q5('namespace');

with (q) {
	q.setup = () => {
		createCanvas(400, 400);
	};
	q.draw = () => {
		background(100);
	};
}

Node.js Usage

Node.js support was recently added, please make an issue report if you encounter any problems.

If you're not interested in rendering to a canvas, q5.js can be used in node.js without any additional dependencies. Just use noCanvas() in your sketch and don't call any drawing functions that require a canvas.

If you want to render to a canvas, you'll need to install the canvas and jsdom packages.

npm install canvas jsdom

q5 will automatically load and configure canvas and jsdom if they are installed. Q5, cairoCanvas, and JSDOM will be added to the global scope by require('q5').

In node.js, q5's automatic global mode is disabled. To use global mode you need to assign q5 user defined functions like draw and setup to the global object then call new Q5(). q5 will add q5 variables and functions to the global object, just like it adds them to the window object in the browser.

Motivation: Part 1

This section was written by @LingDong-, co-creator of q5.

After having used many graphics libraries across many different languages, I have found that the Processing/p5.js/Openframeworks system has one huge advantage over others:

It gets stuff drawn onto the screen quick and easy!

This might sound silly, but it actually means a lot for people concerned with creative expression. The easier it is to try things out, before one's time and patience is up, the greater chance that you'll get something nice in the end. Therefore, although you can theoretically achieve the exact same result in any decent graphics system, the tool does matter in practice. Artists want more time to spend actually working on how their piece looks, instead of wondering why the computer doesn't work as intended.

At Carnegie Mellon University, where I studied computational art, p5.js is taught as the framework for the web, and its been a great introduction. However, due to some of the ways in which p5.js is implemented, I found myself using it less and less as I made more and more projects. Lately, I've found that I'll reach directly for the standard JavaScript/Web APIs instead of p5.js. I sometimes think of this as shedding the training wheels on one's bicycle. But I missed the artist-centered logic of the p5 interface! I started thinking, "Is there a better way?"

Just to clarify, I think the official p5.js implementation is perfectly justified for its philosophy and suitability for its intended purpose, but my own needs are different enough that I think they justify another implementation instead of pull requests to the official one.

In fact, its not uncommon for successful software systems to have multiple implementations of the same spec (think: compilers of C, implementations of SQL, and engines of JavaScript). This allows the user to choose a backend that best suits their goals or needs. When one is using p5.js (or Processing or OpenFrameworks), what one is really using is the same set of commands, the intuitive way of describing drawings, that empowers creative expression. The actual way these commands are implemented internally is incidental; it should be possible to swap internal implementations as necessary.

Motivation: Part 2

This section was written by @quinton-ashley, co-creator of q5.

I thought @LingDong-'s work on q5 and the idea itself had great potential, so I decided to implement more of the p5.js API. My main goal was to make it work with p5play!

An increase in performance of even a few frames per second can make a significant difference in the user experience of a work of interactive art or a game, especially on mobile devices.

I was also interested in working on q5 because for a lot of p5.js users, the library itself is a black box. Even as an expert JS programmer and someone who teaches CS for a living, I still find myself scratching my head when I look at the p5.js source code. p5 was initially released 10 years ago and bad design choices were made due to JS limitations at the time. It's also become an absolutely massive library, with literally over 100,000 lines of code and documentation!

I think it'd be better if the canvas mode, webgl mode, Friendly Error System, and accessibility features of p5 were offered in separate files. Yet, the powers that be at the Processing Foundation have made it clear that they don't want to do that. Instead they insist on adding more accessibility features to the base library, which the majority of people just don't need. So q5 is a good alternative that trims out the fat.

Thanks in large part to @LingDong-'s design, q5 is well organized, concise, and utilizes many modern JS features! I think even without inline documentation, the source code is easier for experienced JS programmers to comprehend.

More exclusive features

Features added by @quinton-ashley:

  • opacity(globalAlpha): set the opacity multiplier for anything subsequently drawn to the canvas in a range between 0 (transparent) and 1 (opaque).
  • textCache(enabled): Text image caching is enabled by default. Rotated text is only rendered once, and then cached as an image. This can result in ridiculously high 90x performance boosts for text-heavy sketches. Users don't need to change their code, the text function can be used as normal, q5 takes care of everything behind the scenes.
  • createImage, loadImage, and createGraphics: as a last parameter to these functions, opt (options) object, users can specify canvas context attributes for an image or graphic. opt.alpha is set to true by default.
  • loadSound(file): Returns a Web Audio object with setVolume() and setLoop() functions added to it. Not as powerful as p5.sound, but it's good enough in some cases.
  • ctx: an instance level alias for drawingContext

Features added by @LingDong-:

  • randomExponential() in addition to randomGaussian(): a random distribution that resembles exponential decay.
  • curveAlpha(): manipulate the α parameter of Catmull-Rom curves.
  • relRotationX, relRotationY and relRotationZ: Similar to rotationX/Y/Z, but are relative to the orientation of the mobile device.

Limitations

  • color function only accepts numeric input, hex, and simple named colors. It doesn't parse strings like color('hsl(160, 100%, 50%)'). This was done to keep the codebase small and easier to understand.

Size Comparison

Unminified:

  • p5.js 4300kb ⚠️
  • p5.sound.js 488kb
  • q5.js 66kb

Minified:

  • p5.min.js 1000kb
  • p5.sound.min.js 200kb
  • q5.min.js 42kb 🎉

Benchmarks

q5.js has a significant speed advantage in imaging operations because it uses hardware accelerated Canvas APIs whenever possible, instead of going pixel by pixel. Most other functionalities have very marginal speed improvements (or none at all when parameter validation overhead is negligible). The operations with important performance differences are listed below.

The following benchmarks are generated with Google Chrome 120, on a MacBook Air M1 2020. q5.js v1.9.3 vs p5.js v1.9.0.

Less time (milliseconds) is better.

Task p5.js q5.js
Generate 10,000 random colors with color(r,g,b) 33ms 3ms

Older Benchmarks

The following benchmarks are generated with Google Chrome 84, on an old-ish MacBook Pro 2015 (with lots of apps and tabs running); Performance varies depending on software and hardware. p5.js version used is v1.1.9.

Higher FPS (frames per second) is better.

Operation on 1024x1024 image p5.js q5.js
tinting 20FPS 35FPS
blurring(11px) 0FPS 40FPS *
thresholding 10FPS 40FPS *
grayscaling 10FPS 50FPS *
inverting 10FPS 50FPS *
opaque 20FPS 60FPS
erode/dilate 5FPS 9FPS
Task p5.js q5.js
Generating 10,000 randomGaussian() sample 10FPS 20FPS
Calling noiseSeed() 1,000 times 10FPS 60FPS
Generate 10,000 (random) colors with color(r,g,b) 5FPS 60FPS
Rotate a Vector 1,000,000 times 13FPS 60FPS

* Only for browsers that support CanvasRenderingContext2D.filter (75% of all as of Aug 2020, including Chrome, Firefox and Edge). For those that don't, performance is similar to p5.js, as identical implementations are usually used as fallbacks.

Contributing

Speed is a goal for q5.js, and we would very much like to see the above list grow. If you know how to make something faster, advice/pull requests are very welcome!

Licensing

q5.js is not affiliated with the Processing Foundation. p5.js is licensed under the LGPLv2, the two small sections of p5.js' code were directly copied into q5.js are credited below. The rest of q5 is a new implementation of part of the p5.js API. APIs are not copyrightable in the United States, as decided by the Supreme Court in the Google v Oracle case.

@LingDong- created the original q5xjs library and licensed it under the MIT license.

@quinton-ashley created q5.js (this project) which contains many bug fixes, additional p5.js API implementations, and several exclusive features. q5.js is licensed under the AGPLv3.

Credits

catmullRomSpline: https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline

ziggurat: http://ziggurat.glitch.me/

random: https://github.com/processing/p5.js/blob/1.1.9/src/math/noise.js

Curve query: https://github.com/processing/p5.js/blob/1.1.9/src/core/shape/curves.js

q5.js's People

Contributors

quinton-ashley avatar ormaq avatar datkat21 avatar

Stargazers

Kelly avatar Vincent Esche avatar Samir Ghosh avatar Katherine Yang avatar Lee T avatar  avatar Frosetrain avatar David Alberto Montaño Fetecua avatar Scott Walter avatar  avatar Marilia Henriquez avatar Daniel Wygoński avatar Metamere avatar Sebastian Laclé avatar  avatar Ryan Barrett avatar James Robb avatar munus avatar Eito Kochi avatar Arne Koenig avatar Noah Betzen avatar Sami ur Rahman avatar Rob Duarte avatar Sofia Mesa Giner avatar Brian Peiris avatar Hoang Tran avatar Dan Sikes avatar Joseph Bacal avatar  avatar  avatar Matias Vazquez-Levi avatar Adrien Fabre avatar  avatar Tim Jüdemann avatar Subodh Pareek avatar Daniel Chicchon avatar Anders Ekelund avatar Milton Edwin Cobo Cortez avatar Werllen Castro avatar

Watchers

James Cloos avatar GoToLoop avatar  avatar  avatar

q5.js's Issues

Refactor `color` and add support for oklch

I want to refactor Q5.Color and the color function to add support for HDR colors, make oklch a new color mode, and remove HSB/HSV support.

p5 devs are planning to improve how color is handled in p5.js v2. I'd like them to take a look at my goals for the color improvements I will make in q5 v1.9.3. Hopefully some of these changes can be made in p5 as well!
processing/p5.js#6680

@limzykenneth @lindapaiste @Vishal2002 @JustZambetti @davepagurek @hellonearthis @meodai

Maintain good performance

q5 is 11x faster than p5 at creating 10,000 random colors: 3ms vs 33ms.

function randomColors() {
    for (let i = 0; i < 100000; i++) {
        let c = color(random(255), random(255), random(255));
    }
}

const start = performance.now();

randomColors();

const end = performance.now();
console.log(`Execution time: ${end - start} ms`);

What kind of magic is q5 using to achieve such results? q5 simply doesn't do any unnecessary color format conversions. Since the default color mode is RGB, q5 simply stores the user's rgb values as properties in a object.

But in p5, the user's legacy rgb 0-255 range input is converted to modern 0-1 range rgba values, both of which are stored in arrays. maxes arrays for each color format are also copied into every color object, which seems unnecessary. hsba and hsla are both defined on the object as null, even if the user doesn't intended to convert the color.

Make color components easier to view and edit

If you view a p5.Color in the console, you'll probably be confused by the output! Especially if you're a beginner programmer.

{
	hsba: null,
	hsla: null,
	levels: [255, 10, 82, 255],
	maxes: {
	  hsb:  [360, 100, 100, 1],
	  hsl: [360, 100, 100, 1],
	  rgb: [255, 255, 255, 255]
	},
	mode: 'rgb',
	_array: [1, 0.0392156862745098, 0.3215686274509804, 1]
}

To try to understand why p5.Color was implemented this way, we have to study its grandaddy: Processing.

In Java Processing, the color method generated a primitive int, not an Object, and in Java ints can't have properties or methods. That's why the red, green, blue, alpha functions were necessary. Those individual color components could only be retrieved from a color int through bitwise operations, not via properties.
https://forum.processing.org/two/discussion/15923/how-to-change-alpha-without-changing-the-whole-color.html

But in p5 these functions should've only been implemented for backwards compatibility. Thankfully color.setRed() and similar functions were introduced, but why not a color.getRed() or better yet expose the color components as public properties?

To improve q5 I'm taking inspiration from the popular JS color library culori represents colors as objects with letter properties, using a single color mode per object, making them easy to view and edit.

// culori.js rgba color data representation
{
  r: 255,
  g: 10,
  b: 82,
  a: 1,
  mode: 'rgba'
}

oklch support

But just making red, green, and blue components easier to edit doesn't fix the more fundamental problems with the RGB format. As noted in the article "OKLCH in CSS: why we moved from RGB and HSL":

"RGB, hex and color(display-p3) aren’t convenient for color modifications because, for the vast majority of humans, it’s difficult to intuitively set colors by changing the amount of red, blue and green. Further, RGB and hex also can’t encode P3 colors."

I recommend reading the full article, it's great! I'm going to make separate classes for rgb and oklch that extend Q5.Color, so that instanceof p5.Color checks can still work.

Currently Q5.Color instances internally output color to ctx.fillStyle or ctx.strokeStyle via their toString method. For Q5.ColorRGBA and Q5.ColorOKLCH their toString() functions won't require any calculations.

Auto-upgrade RGB to HDR

While I do think oklch is the future, I don't really expect any Intro to Web Design class/section to teach oklch anytime soon. But I want to get people using HDR colors today!

I think the best way to do this is to create a backwards compatibility class, Q5.ColorRGBA_P3. Users can still edit colors using the default RGB colorMode but the resulting colors will be internally mapped directly to the HDR "display-p3" color space in toString using this format: color(display-p3 r g b / a).
https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/color

To prevent toString from needing to do the format conversion from the legacy 0-255 range to the modern 0-1 range whenever toString is used, I'll create getter/setter properties for the purpose of watching for changes. Only when the color is changed will toString do new calculations.

Let users make colors using new Color()

p5.Color is not a class that belongs to a p5 instance but rather p5 itself. q5 mimics this implementation.

Yet,_colorMode is an instance variable, so it can't be accessed directly by the p5.Color constructor. p5 gets around it by passing p5 instances to the p5.Color constructor. Additionally, in q5 I'll need to access the canvas to get the canvas' color space. In q5, all of the color parsing code is done in the q5 instance level color function. I will maintain this structure.

Depending on the instance's current color mode and canvas color space, the q5 instance variable $.Color will be set to Q5.ColorRGBA, Q5.ColorRGBA_P3, or Q5.ColorOKLCH. These constructors will have no parsing overhead.

Remove HSB/HSV support

Support for the HSV color format will be removed in q5 v1.9.3 because it was rarely used, the amount of code required to convert between RGB and HSV was quite large, and color experts considered HSV to be flawed and outdated way back in 1997!

https://en.wikipedia.org/wiki/HSL_and_HSV#Disadvantages

Bug with transparency in sprites in version 1.9x

Code:

var player;

function preload() { 
  new Canvas("2:5"); 
   
  player = new Sprite(100,100);  
  //player.spriteSheet = loadImage("questKid.png");
  player.spriteSheet = "https://p5play.org/learn/assets/questKid.png";
  player.w = 32;
  player.h = 32;    
}

function setup() {	 
  background("blue"); 

  player.addAnis(
    {
      right:{row:0, frames: 8},
      left:{row:1, frames: 6},      
      down:{row:2, frames: 5},
      up:{row:3, frames: 7},      
      kuv:{row:4, frames: 8},      
    }
  )    
}

function draw() {
  clear();
  background("blue"); 

	if (kb.presses("r")) player.changeAni("right");
	if (kb.presses("j")) player.changeAni("left");
	if (kb.presses("l")) player.changeAni("down");
	if (kb.presses("t")) player.changeAni("up");
	if (kb.presses("s")) player.changeAni("kuv");  
}

If you use version q5.js 1.9.9:
sprite

If you use version q5.js 1.8.7:
sprite2

pixel fonts not rendered properly

Yeah... this is a bit of a rabbit hole! 🐰

q5.js currently can't render pixel fonts (very small sized fonts made of just a few pixels) at a pixel perfect level (sharp and blocky) because q5 uses native canvas rendering. Every browser's canvas.fillText implementation seems to do anti-aliasing and the ctx.textRendering property doesn't seem to change that, at least not in Chromium based browsers. Also Safari does not have this feature. https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/textRendering

p5.js can sometimes render pixel fonts correctly, if the font is the right size and at a correct position (not always integer coordinates!). p5 does not use native canvas rendering for true type and open type fonts, it uses OpenType rendering. My guess is that this decision was made because around the time p5.js was created, browser's native canvas implementations for font rendering were not so good. Nowadays though, in any other case besides pixel fonts, q5's native canvas rendering with canvas.fillText definitely looks better and probably runs faster than p5's OpenType based method. Which I noted here:
https://discourse.processing.org/t/why-is-text-not-centered-properly-with-textalign-center-center/43322/8

However, in the case of pixel fonts, using OpenType to render text as primitive canvas shapes actually works great because pixel fonts are just made out of a few pixels (squares). So OpenType rendering could be used for pixel fonts and native for everything else? Well things are not so simple.

Take a look at this demo with a font called Bit Potion, the creator says it's best to use it in 16px intervals. I made this demo which uses p5.js and shows text displayed with the pixel font at 16px and 32px.

https://editor.p5js.org/quinton-ashley/sketches/fhr7cLd3R

Clicking the mouse in the demo will switch the text from being rendered at integer coordinates to half pixel coordinates (0.5). For some reason, at any even multiple of 16px, such as 32px, text only looks good at integer coordinates. At any odd multiple of 16 such as 48px or 16px, text only looks good at half pixel coordinates and only without letters that hang under the baseline like "p".

Why is that? Well I found this old stack overflow post where a user says "the canvas coordinate system defines the start of a pixel from the pixel's center" https://stackoverflow.com/questions/22976031/html5-canvas-without-anti-aliasing?rq=3

This sucks for users. Displaying pixel fonts shouldn't be a difficult guessing game. Users should just be able to put in any random coordinates and as long as the font is the right size, q5 should be able to draw it with pixel precision (sharpness).

But how could such a generalized solution be achieved? I don't know yet.

One idea is to add a feature to p5 and q5 where users could define the optimal size of a font. Then when the text function was used with the font, there could be some code that could adjust the position given by the user to make the font display well.

Another totally differnt idea I had was that p5play users could import a pixel font as a spritesheet animation, provided the font offer an image containing all the font's symbols. Then text could be displayed using the Tiles constructor. However, this has many obvious limitations. It'd only work for monospace fonts, not for the "Bit Potion" font. Also this method is untenable for non-English text with accented letters. Also it'd make using the Tiles constructor for anything else pretty much impossible. Yet, this approach could be decent for English text as long as it was implemented as a separate system to not conflict with p5play's Tiles system.

But I also noticed the Bit Potion font is offered as an old bitmap .fnt windows font file. I wonder if there's any canvas library for rendering them? This could be a good solution. I will research this more.

vec.normalize() is incorrect if values have changed

Looks like q5's optimizations don't account for changes to a vector's components.

var vec = new p5.Vector();

vec.x = 2; 
vec.normalize();
console.log(vec.x); // gives 1

vec.y = 1;
vec.normalize();
console.log(vec.x) // gives 0.707 in p5, but still 1 in q5

Support for HDR displays

Motivation:

I want users to be able to use more vibrant HDR colors in their q5.js projects.

Check out my HDR web design guide for more info:
https://quinton-ashley.github.io/hdr-web-design-guide/

HTML5 canvas contexts can use the "display-p3" HDR color space but p5.js doesn't support it.
https://developer.mozilla.org/en-US/docs/Web/API/ImageData/colorSpace

https://webkit.org/blog/12058/wide-gamut-2d-graphics-using-html-canvas/

Implementation:

I want to make "display-p3" the default color space in q5.js, as long as the user's device is capable. Most devices made after 2017 are!
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_media_queries/Testing_media_queries

A canvas' color space can be set via canvas context attributes #23

But properly supporting HDR isn't as simple as just changing the color space. I also need to give users a way to use HDR colors. In CSS the format for hex rgba, legacy rgba, srgb, and display-p3 are all different.

I think q5's color system needs to be rewritten #24

colorMode

Hello. I try to test q5.js in replacement of p5.js for a website (only some small colors image conversion).
On p5js, I manage to do it with a HSL colorMode.

On q5js, there are only RGB mode and HSB mode. It is true?

multi-line text not vertically centered with textAlign

This example uses p5play.

function setup() {
	new Canvas(400, 400, 'pixelated');
	background(220);
}

function draw() {
	background(220);

	translate(canvas.hw, canvas.hh);
	textAlign(CENTER, CENTER);
	textSize(100);
	text('hello\nbye', 0, 0);
}

tinting is broken

Somehow I broke tinting in the latest version of q5. Will fix ASAP!

heading()

From the flocking p5 example

this.velocity = p.createVector(p.random(-1, 1), p.random(-1, 1));

let theta = this.velocity.heading() + p.radians(90);

Upon calling this code we get that $ is not defined

you can fix this using

heading() {
		let $ = this;
		return Math.atan2($.y, $.x);
	}

but this is not a pretty solution * And does not really work*

normalize() doesn't return the same as p5

I've been testing the following sketch. I've debugged al the way until normalize() (line 80), which results in a NaN. If I comment out the normalize it starts working for a couple of frames but runs in to more issues.

Stopped debugging here but this might be a good test case to find some more discrepancies

`resizeCanvas` fails on mobile device orientation change

Here's the example using p5play that isn't working.

Strangely this issue only occurs in Safari and not in the iOS app template that I'm working on.

I can't figure out what's wrong compared to p5's implementation.

let boxes = {};

function setup() {
	new Canvas();
}

function draw() {
	background(16);

	renderStats();

	textSize(24);
	textAlign(CENTER);
	fill(200);
	text('Tap to create a new sprite', canvas.hw, canvas.hh);

	let info = canvas.w + 'x' + canvas.h + ' X' + pixelDensity() + ' ' + deviceOrientation;
	text(info, canvas.hw, canvas.hh + 30);

	for (let touch of touches) {
		if (touch.presses()) {
			let box = new Sprite(touch.x, touch.y, 30, 30);
			boxes[touch.id] = box;
		} else {
			boxes[touch.id].moveTowards(touch);
		}
	}
}

function windowResized() {
	canvas.resize();
}

Tint caching

Looking over the code at school at the moment- tinted images seem to create their offscreen canvas, apply filters, then draw- every frame. If the tint stays the same, it makes sense to cache the canvas with the image, for quick drawing for subsequent frames. This would also help with changing tints, as they could simply change the pre-existing canvas without the need for overhead creating more canvases.

CreateP is not yet available ?

I love your library! I tested it with some of my sketches but notice that some functions are still missing, like createP. Or am I missing something?

`curveTightness` behaviour

Co-author @lingdong~ wrote:

curveTightness() sets the 'alpha' parameter of Catmull-Rom curve, and is NOT identical to p5.js counterpart. As this might change in the future, please call curveAlpha() directly.

Implement `sound.setPan`

My goal is for q5.js to have basic sound support so users don't need to load p5.sound if they don't need to. See loudSound for the current implementation.

I think setPan would be a great addition but I couldn't yet figure out how to do it. If anyone wants to implement this let me know!

Set canvas context attributes

Motivation:

Users should be able to set canvas context attributes.

p5.js currently doesn't expose the ability to change 2d canvas context attributes. They can only be changed when the canvas is created and getContext is used for the first time.

I'm especially interested in being able to set new defaults for q5.js:

Q5.canvasOptions = {
	alpha: false,
	desynchronized: true,
	colorSpace: 'display-p3'
};

alpha: most sketches do not take advantage of the canvas element's transparency and disabling it would improve performance

desynchronized: most sketches would benefit from desynchronization with the DOM, unless the sketch used DOM elements above the canvas.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext
https://developer.chrome.com/blog/desynchronized

colorSpace: If the display supports "display-p3" I want q5 to use it. #21

Related issue:
processing/p5.js#5902

Implementation:

This could be done via a createCanvas input parameter. For example:

createCanvas(800, 600, '2d', {
  alpha: false
}); 

Users could also change the defaults held in Q5.canvasOptions which would have an effect on all instances of q5. I will need to do this on p5play.org because I actually do take advantage of the canvas's alpha via the clear function which makes light and dark mode possible on the site without needing to change the example code.

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.