Search code examples
canvasthree.jsplane

I want to insert these rectangles in the PlaneGeometry as many I can but not able to achieve it?


I want to show rectangles as per my requirements in the planeGeometry as shown in images. enter image description here

I was able to achieve this rectangle using ctx.strokeReact from canvas 2d as shown below in images. enter image description here

Here is the code, for adding 5 rectangle using for loop but I'm getting only one rectangle on planeGeometry.

createStroke = (j) => {

var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = "white";
ctx.strokeStyle = "white";
ctx.lineWidth = 2;
console.log("j is " + j);
ctx.strokeRect(10 + j, 5, 30, 30);

return ctx;

 }

 let ctxArr = [];
let texture;
var j = 0;

for (var i = 0; i < 5; i++) {

  ctxArr[0] = this.createStroke(j);
  j = j + 2;

}


console.log("ctxArr[0].canvas " + new THREE.CanvasTexture(ctxArr[0].canvas))

texture = new THREE.CanvasTexture(ctxArr[0].canvas);

var planeGeo = new THREE.PlaneGeometry(5, 6);
var planeMaterial = new THREE.MeshBasicMaterial(
  {
    map: texture,
    // wireframe: true
  }
);

// planeGeo.rotateY(1);

var plane = new THREE.Mesh(planeGeo, planeMaterial)
// plane.material.color.setHex( 0xf7d36f );

plane.position.set(3, 0, 0)
// plane.rotateX(-Math.PI / 2.0);
// plane.copy();
this.scene.add(plane);

How to achieve the functionality for the same as first image. Any help , guidance, reference or suggestion would be helpful. Thanks


Solution

  • Not quite sure why you are mixing three.js into this simple problem...

    Going to focus only on getting something that resembles your image.
    First if you need rectangles the width and height should be different you have:
    ctx.strokeRect(10 + j, 5, 30, 30)

    • that will make squares
    • you hardcoded the y to 5
    • the j is only increasing by 2, that will be on top of each other

    Here is a simple approach:

    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    ctx.strokeStyle = "red";
    ctx.lineWidth = 2;
    
    createRect = (x, y) => {
      ctx.strokeRect(x, y, 30, 40);
    }
    
    for (var x = 5; x < 180; x += 35) {
      for (var y = 5; y < 120; y += 45) {
        createRect(x, y)
      }
    }
    <canvas id="canvas"></canvas>