使较小版本的画布成为p5.js中的对象 [英] Making smaller version of canvas an objects in p5.js

查看:0
本文介绍了使较小版本的画布成为p5.js中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在尝试在p5.js中制作我的画布和精灵的一个精确的更小的版本,并将其放入一个盒子中。有什么功能或方法可以做到这一点吗?精灵的背景、颜色和图像应该相同。

推荐答案

有两种方法可以做到这一点,一种方法是将所有内容绘制到p5.Graphics缓冲区,然后将该缓冲区绘制到具有不同目标大小的主画布两次。另一种方法是将绘图的主要部分直接绘制到画布上,然后使用pixels数组从画布内容创建p5.Image,然后使用image函数将其绘制到画布上。

示例1.p5.Graphics

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
let graphics;

function setup() {
  createCanvas(windowWidth * 0.9, windowHeight * 0.9);
  graphics = createGraphics(width, height);

  graphics.background(100);
}

function draw() {
  graphics.ellipse(mouseX, mouseY, 50, 50);

  image(graphics, 0, 0, width, height, 0, 0, graphics.width, graphics.height);

  // Draw picture in picture
  let aspect = width / height;
  image(graphics, 10, 10, 100, 100 / aspect, 0, 0, graphics.width, graphics.height);
  push();
  noFill();
  strokeWeight(3);
  rect(10, 10, 100, 100 / aspect);
  pop();
}
<!DOCTYPE html>
<html lang="en">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>
</head>

<body>
</body>

</html>

示例2.像素和图像

注意:此选项的缺点是更复杂、等待速度较慢,而且它不支持永久绘制的内容以及p5.Graphics选项,因为它会在后续帧中显示自己。

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
let img;
let density;

function setup() {
  createCanvas(round(windowWidth * 0.9), round(windowHeight * 0.9));
  density = pixelDensity();

  img = createImage(width, height);
  img.loadPixels();

  background(100);
}

function draw() {
  ellipse(mouseX, mouseY, 30, 30);

  loadPixels();
  for (let x = 0; x < width; x++) {
    for (let y = 0; y < height; y++) {
      let srcPixel = y * 4 * width * density ** 2 + x * 4 * density;
      let dstPixel = y * 4 * img.width + x * 4;
      for (let channel = 0; channel < 4; channel++) {
        img.pixels[dstPixel + channel] = pixels[srcPixel + channel];
      }
    }
  }
  img.updatePixels();

  // Draw picture in picture
  let aspect = width / height;
  image(img, 10, 10, 100, 100 / aspect, 0, 0, img.width, img.height);
  push();
  noFill();
  strokeWeight(3);
  rect(10, 10, 100, 100 / aspect);
  pop();
}
<!DOCTYPE html>
<html lang="en">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>
</head>

<body>
</body>

</html>

这篇关于使较小版本的画布成为p5.js中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆