[PYTHON] Getting Started with Processing and p5.js (for those who have done other languages) 02

What is p5.js

A javascript library (like) that can use Processing on the Web I'm the savior of people who want to publish what they made with Processing for the time being, but can't.

Python and Flask

Now, write the server side in Flask of python. Flask is a micro-framework for the web provided for python. Anyway, the introduction cost is low. It's really easier to introduce than dj 〇 ngo. It's really easy. (Although the material is old and there are some annoying parts)

Sample code

Immediately from somewhere ~~ I got it ~~ I will make it based on the reference code. It's an introduction so I won't touch any difficult things (because I'm a beginner myself)

The movement is the same as the previous article.

Python code

app.py


from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)
@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run()

(If you think about it, you don't need to use python with this implementation ...)

html code

layout.html


<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>p5.js</title>
    <link href="/static/css/bootstrap.min.css" rel="stylesheet">
    <script src="//cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.8/p5.js"></script> <!--Please correct this in a timely manner. Whether you drop it or use it on the network-->
    <script src="/static/js/kurukuru.js"></script>
    <style type="text/css">
      * {margin: 0;}
      * {padding: 0;}
    </style>
  </head>
  <body>
    {% block content %}{% endblock %}
    <script src="/static/js/jquery.min.js"></script>
    <script src="/static/js/bootstrap.min.js"></script>
  </body>
</html>

index.html


{% extends "layout.html" %}
{% block content %}
  <!-- Form
  ================================================== -->
<div class="form">
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-12">
        <p>
          <div id="p5Canvas">
            <p></p>
          </div>
        </p>
      </div>
    </div>
  </div>
</div>
{% endblock %}

javascript file

kurukuru.js


const N = 20;

let p_x = [];
let p_y = [];
let p_pX = [];
let p_pY = [];

let p_distances = [];
let p_gap_theata = [];

let p_colors = [];

let p_frameCount;

function setup(){
  let canvas = createCanvas(windowWidth, windowHeight);
  canvas.parent("p5Canvas");
  background(255);

  colorMode(HSB, 255, 100, 100);

  p_frameCount = 0;
  noStroke();

  for(var i = 0; i < N; i++){
    p_x.push(30);
    p_pX.push(30);
    p_y.push(30);
    p_pY.push(30);
    p_distances.push(random(15, 150));
    p_gap_theata.push(random(-PI, PI));

    p_colors.push(color(random(255), 100, 100));
  }
}
function draw(){
  colorMode(RGB, 255);
  background(255);
  colorMode(HSB, 255, 100, 100);
  for(var i = 0; i < N; i++){
    fill(p_colors[i]);
    let theata = radians(p_frameCount*5.0) + p_gap_theata[i];
    let dist =p_distances[i] + 90.0*noise(theata/1.0, p_frameCount/100.0)
    p_x[i] = (mouseX + dist*cos(theata) + p_pX[i])/2.0;
    p_y[i] = (mouseY + dist*sin(theata) + p_pY[i])/2.0;
    ellipse(p_x[i], p_y[i], 20, 20);
    p_pX[i] = p_x[i];
    p_pY[i] = p_y[i];
  }
  p_frameCount++;
}

function windowResized(){
  resizeCanvas(windowWidth, windowHeight);
}


reference

I'm dropping the previous Processing code into javascript. What can be a global variable is p_ It depends on how you feel, but if you are familiar with javascript and Processing, you will feel comfortable with it.

let canvas = createCanvas(windowWidth, windowHeight);
canvas.parent("p5Canvas");

I think this is the key. I think it was a little more difficult to fill the screen when Processing.js, but p5.js is smooth. You can also specify the id of the canvas to be displayed. If canvas exists without this, it will be associated with it normally. Reference URL

However, when the screen size is changed, the display area does not change at the original size.

function windowResized(){
  resizeCanvas(windowWidth, windowHeight);
}

Add this. Reference URL

You can also use mouseX, ʻelipse, and colorMode`. Sounds good.

** People from other js libraries may not be used to it, but if you do not initialize the screen (bacground) in draw, the previous drawing will remain. ** **

If you want to initialize the drawing, but want to keep the drawing behind the canvas, you can devise background. When entering 4 variables

background(r, g, b, α)

Because it should be, you should be able to change the remaining condition of the previous drawing depending on the value of α. (I lost the code I tried)

Conclusion

Fun

bonus

Before p5.js, there was something called Processing.js. In Processing.js, you can use the Processing code as it is.

I don't think anyone will get it, but I'll leave it.

index.html


<!DOCTYPE html>
    <head>
       <script src="processing.js"></script>
       <script>
         window.onload = function(){
           var canvas = document.getElementsByTagName('canvas')[0];
           var codeElm = document.getElementById('processing-code');
           var code = codeElm.textContent || codeElm.innerText;

           new Processing(canvas, code);
         };
       </script>
       <script id="processing-code" type="application/processing">
         void setup() {
           size(innerWidth, innerHeight);
           frameRate(20);
         }
         void draw() {
           size(innerWidth, innerHeight);
           background(0, 0);
           ellipse(width/2, height/2, mouseX, mouseY);
         }
       </script>
    </head>
    <body bgcolor="ffccff">
    	<div id="wrapper">
    		<canvas id = "main"></canvas>
    	</div>
    </body>
</html>

main.css


body{
	margin: 0px;
	padding: 0px;
	position: relative;
}

body #wrapper{
	width: 100%;
	height: 100%;
	position: fixed;
}

resize.js


$(function(){
	sizing();
	$(window).resize(function(){
		sizing();
	});
});

function sizing(){
	$("#main").attr({height:$("wrapper").height()});
	$("#main").attr({height:$("wrapper").width()});
}

The maximization process is performed in the last js file.

Recommended Posts

Getting Started with Processing and p5.js (for those who have done other languages) 02
Getting Started with Processing and p5.js (for those who have done other languages) 01
For those who have done pip uninstall setuptools
For those who want to learn Excel VBA and get started with Python
5 Reasons Processing is Useful for Those Who Want to Get Started with Python
[For those who have mastered other programming languages] 10 points to catch up on Python points
Getting Started with Python for PHPer-Classes
Getting Started with Julia for Pythonista
Getting Started with Python for PHPer-Functions
Getting Started with Python for PHPer-Super Basics
Getting Started with Lisp for Pythonista: Supplement
Join Azure Using Go ~ For those who want to start and know Azure with Go ~
[Solved] I have a question for those who are familiar with Python mechanize.
Getting started with Python with 100 knocks on language processing
[Translation] Getting Started with Rust for Python Programmers
Settings for getting started with MongoDB in python
❤️ Bloggers ❤️ "Beloved BI" ❤️ Let's get started ❤️ (For those who can make charts with Python)
For those who are new to programming but have decided to analyze data with Python
For those who should have installed janome properly with Python but get an error
Getting Started with python3 # 2 Learn about types and variables
Getting Started with Google App Engine for Python & PHP
Getting Started with Tensorflow-About Linear Regression Hypothesis and Cost
For those who want to write Python with vim
For those who get Getting Key Error:'length_seconds' on pytube
Getting Started with Yocto Project with Raspberry Pi 4 and WSL2
Getting started with Android!
1.1 Getting Started with Python
Getting Started with Golang 2
Getting started with apache2
Getting Started with Golang 1
Getting Started with Python
Getting Started with Django 1
Getting Started with Optimization
Getting Started with Golang 3
Getting Started with Numpy
Getting started with Spark
Getting Started with Python
Getting Started with Pydantic
Getting Started with Golang 4
Getting Started with Jython
Getting Started with Django 2
For those who want to start machine learning with TensorFlow2
A modern environment building procedure for those who want to get started with Python right away