如何通过p5.js中的矩形查看?

时间:2019-07-24 23:13:16

标签: javascript p5.js

我正在尝试创建一种效果,您可以用鼠标悬停在网页上,该网页上将有一个图形,并且当您到达某个区域时,可以显示图像。我考虑过这样做:

  • 背面有图像
  • 在其上具有一个矩形(以将其隐藏)
  • 具有一个元素(您的鼠标)可以越过矩形并删除鼠标悬停在其上的部分。

如何使用p5.js做到这一点?

此刻我将其显示在屏幕上

    let img;

// function preload() {

// }

function setup() {
  var canvas = createCanvas(
    document.getElementById("myCanvas").offsetWidth,
    document.getElementById("myCanvas").offsetHeight
  );
  canvas.parent("myCanvas");
  // background(32);
  loadImage("../img/monalisa.png", img => {
    image(img, 0, 0);
  });
}

function draw() {
  //   monaLisa();
  rect(0, 0, 300, 300);
  circles();
}

// function monaLisa() {
//   image(img, 0, 0);
// }

function circles() {
  //   fill(255);
  ellipse(mouseX, mouseY, 25, 25);
}

1 个答案:

答案 0 :(得分:0)

只需将鼠标从左侧放置到像素左右,即可向右推动该矩形。

let img;
let edgeX = 0;

function setup() {
  createCanvas(300,400)
  img = loadImage("https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/300px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg")
}

function draw() {
  // variable updates
  if (mouseX > edgeX && 
      mouseX >= 0 && mouseX <= 300 && // mouse within limits of picture
      mouseY >= 0 && mouseY <= 400
     ) {
     edgeX = mouseX;
  }

  // actual  rawing
  image(img, 0, 0);
  fill('rgba(50,255,150, 0.5)');
  rect(edgeX, 0, 300, 400);
}

p5 demo

编辑

如果您只想在鼠标位置下发现一小段图片,那么可能是这样的:

  1. 创建2D矩形数组
  2. 遍历矩形并将其绘制在图像上方
  3. 如果鼠标与某个矩形相交-将其标记为不可绘制

代码:

let canvW = 300
let canvH = 400
let img
let dx = 20
let dy = 40
let diff = 3
let blocks

function setup() {
  cursor(CROSS);
  mouseX = -10;
  mouseY = -10;
  createCanvas(canvW,canvH)
  img = loadImage("https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/300px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg")
  blocks = new Array(canvH/dy);
  for (var i=0; i < blocks.length; i++) {
     blocks[i] = new Array(canvW/dx);
  }
}

function draw() {
  // variable updates
  for (var y=0; y < blocks.length; y++) {
    for (var x=0; x < blocks[y].length; x++) {
       if (mouseX >= dx*x && 
           mouseX <= dx*x+dx &&
           mouseY >= dy*y && 
           mouseY <= dy*y+dy
          ) {
         blocks[y][x] = false;
       }
    }
  }

  // actual drawing
  image(img, 0, 0)
  stroke(70,127,240, 100)
  strokeWeight(3)

  for (var y=0; y < blocks.length; y++) {
    for (var x=0; x < blocks[y].length; x++) {
       if (blocks[y][x] !== false) {
         // outer rectangle
         fill(`rgba(50,127,240, 0.5)`)
         rect(dx*x, dy*y, dx, dy)
         // inner rectangle
         fill(`rgba(70,127,240, 0.8)`)
         rect(dx*x+diff, dy*y+diff, dx-2*diff, dy-2*diff)
       }
    }
  }
}

p5 uncover segment demo

视觉效果:如果有人懒于查看演示,部分发现蒙娜丽莎:

enter image description here