Me gustaría crear una clase con una matriz de objetos en el constructor. La idea es crear rectas en un lienzo con los valores dentro de los objetos.
Tengo esta matriz:
const blueBoxs = [ { x: 38, y: 31, w: 50, h: 50 }, { x: 47, y: 31, w: 25, h: 19 }, ]Intenté lo siguiente:
class Collision { constructor (boxs) { this.boxs=boxs; }; createBox(boxs=[]){ for (let box of boxs) { ctx.fillStyle = 'blue' ctx.fillRect(box.x, box.y, box.w, box.h) } return }; }; let createBluebox= new Collision(blueBoxs); createBluebox.createBox();Gracias por tu ayuda.
Como ya se ha escrito, la adición de this funciona. Ver ejemplo con this.boxs
const blueBoxs = [ { x: 38, y: 31, w:50, h:50, }, { x: 47, y: 31, w:25, h:19, } ] class Collision { constructor (boxs) { this.boxs=boxs; }; createBox(boxs=[]){ for (let box of this.boxs) { ctx.fillStyle = 'blue' ctx.fillRect(box.x, box.y, box.w, box.h) } return }; }; let canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); let createBluebox= new Collision(blueBoxs); createBluebox.createBox(); <canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML5 canvas tag.</canvas>Olvidé this palabra clave en todas partes. ¡Gracias por todo!
class Collision { constructor (boxs, ctx) { this.boxs=boxs; this.ctx=ctx; }; createBox(){ for (let box of this.boxs) { this.ctx.fillStyle = 'blue' this.ctx.fillRect(box.x, box.y, box.w, box.h) } return }; }; let createBluebox= new Collision(blueBoxs, ctx); createBluebox.createBox();