如何将处理整合到我的网页中

问题描述

我正在尝试将处理(一种图形编程语言)集成到我的网站中,但是代码似乎不起作用。 似乎没有注册处理代码...

有什么想法吗?

    <!doctype html>
<html lang="en">
<head>
    <script type="text/javascript" src="js/processing.js"></script>
    
</head>

<body>
<script type= "text/processing">


int ranges = 100;

void setup() {
  fullScreen();
  background(0);
}

void draw() {
  background(0);
  noFill();
  strokeWeight(1);

  for (int i = 1; i < ranges; i++) {
    float paint = map(i,ranges,1,105);
    stroke(paint);
    
    beginShape();
    for (int x = -100; x < width + 11; x += 20) {
      float n = noise(x * 0.001,i * 0.01,frameCount * 0.01);
      float y = map(n,0.1,mouseY,height);
      vertex(x,y);
    }
    endShape();
  }
}

</script>
 

    <canvas id="sketch" style="border: 1px solid black;"></canvas>

</body>
</html>

解决方法

您不能按原样重复使用处理代码:这是Java代码,无法在网页中执行。要在网页中使用处理功能,您需要使用以下语言的javascript实现:p5.js

getting started页面非常简单。如果您想以最简单的方式进行操作,则可以使用the p5 webeditor

您仍然需要将代码转换为javascript,看起来像这样:

const ranges = 100;
function setup() {
    createCanvas(windowWidth,windowHeight);
    background(0);
}

function draw() {
    background(0);
    noFill();
    strokeWeight(1);
    for (let i=1; i<ranges; i++) {
        let paint = map(i,ranges,1,105);
        stroke(paint);

        beginShape();
        for (let x=-100; x<width + 11; x+=20) {
            const n = noise(x * 0.001,i * 0.01,frameCount * 0.01);
            const y = map(n,0.1,mouseY,height);
            vertex(x,y);
        }
        endShape();
    }
}

主要更改是使用关键字function而不是void声明函数; fullScreen()在p5中不存在,但是您可以创建一个具有窗口宽度和高度的画布(您也可以查看fullscreen()以及类型float和{{1 }}在javascript中不存在,您可以使用intlet声明变量。

在p5编辑器中复制先前的代码将使您入门。现在,如果您想创建自己的html页面,则需要像我之前展示的那样将代码移植到javascript,但是还需要确保包含p5.js框架。一种简单的方法是将您的const脚本替换为托管在CDN上的以下版本:

processing.js

现在,当您在浏览器中打开此html页面时,将看到您的画布。您可能要做的最后一件事是使用本地开发服务器来服务文件,因为这将简化您的未来开发。

这里是一个codepen,我在其中移植了代码,javascript在专用文件中,我认为它将为您开始做您想做的事情提供良好的基础。