在 vue 中使用 p5js 获取给定位置的像素颜色

时间:2021-03-20 14:14:08

标签: vue.js p5.js

我目前在 vue 中使用 p5.js。 为了让它运行,我遵循了 p5.js and vue - create a canvas 中描述的步骤。

这工作得很好,但是在使用 p5 提供的某些功能时我被卡住了。 使用此设置,我如何(例如)在尝试获取给定位置的像素时使用 get 函数。 b.img.get() 不起作用。在“正常”实例中,我可以跳过 b.,但在 vue 中我必须使用它(据我所知)

import * as P5 from 'p5';

export default {
  name: "Pixelation",
  mounted() {
    this.$nextTick(function () {
      let w = document.getElementById("pixel").offsetWidth;
      let h = document.getElementById("pixel").offsetHeight;

      const sketch = b => {

        let img;
        let rad;

        b.preload = () => {
          img = b.loadImage(require('@/assets/tankman.png'));
        }

        b.setup = () => {
          b.createCanvas(w, h);
          b.image(img, 0, 0, w, h);
          rad = 30;
        }


        b.draw = () => {
          for(let i = 0; i < w; i += rad) {
            for (let j = Math.round(h / rad); j < h; h += rad) {
               b.fill(b.img.get(i, b.max(j, 0)));
               b.circle(i, j, rad);
            }
          }
        };
      }

      // eslint-disable-next-line no-unused-vars
      let canvas = new P5(sketch, 'top');
    })
  }
}
#pixel {
  width: 100%;
  height: 100vh;
}
<template>
  <div id="pixel"></div>
</template>

1 个答案:

答案 0 :(得分:1)

我只是严重误解了 b 的方式。必须使用。

使用 b.loadImage(require('@/assets/tankman.png')) 加载图像并将其分配给变量时,可以通过使用 p5 提供的所有所需功能 variable.function(),因为 variabel 已经包含 p5 功能