Javascript JS:调整画布大小+在画布上重画元素

Javascript JS:调整画布大小+在画布上重画元素,javascript,arrays,object,canvas,resize,Javascript,Arrays,Object,Canvas,Resize,我的问题:用所有绘制的元素调整画布大小的最佳方法是什么 我有两个例子,我试图将其归档 第一个可以工作,但缺乏功能,因为如果我要添加更多的元素来绘制,它会变得非常混乱。在我的第二个示例中,我尝试将所有内容放入一个数组中并在其中循环,但它不再正确调整大小,因为它不再重新计算x、y宽度和高度。基本上,我希望知道一种方法,不必在绘图之前再次调用函数来计算元素x、y、宽度和高度。我想把数学放到数组中,当它被画出来的时候, 它会重新计算,所以我只需确保canvas.width/height已更新,我该如何做

我的问题:用所有绘制的元素调整画布大小的最佳方法是什么

我有两个例子,我试图将其归档

第一个可以工作,但缺乏功能,因为如果我要添加更多的元素来绘制,它会变得非常混乱。在我的第二个示例中,我尝试将所有内容放入一个数组中并在其中循环,但它不再正确调整大小,因为它不再重新计算x、y宽度和高度。基本上,我希望知道一种方法,不必在绘图之前再次调用函数来计算元素x、y、宽度和高度。我想把数学放到数组中,当它被画出来的时候, 它会重新计算,所以我只需确保canvas.width/height已更新,我该如何做

第一个例子

类画布{ 建造师{ this.canvas=document.createElement'canvas'; this.canvas.width=window.innerWidth; this.canvas.height=window.innerHeight; this.ctx=this.canvas.getContext'2d'; document.body.appendChildthis.canvas; 这个。调整大小; } 初始区域{ this.firstArea={x:0,y:0,w:this.canvas.width,h:this.canvas.height/2} this.secondArea={x:0,y:this.firstArea.h,w:this.canvas.width,h:this.canvas.height/2} } 调整大小{ this.canvas.width=window.innerWidth; this.canvas.height=window.innerHeight; 这是一个重要的领域; this.ctx.fillStyle=绿色; 这个.ctx.fillrecthis.firstArea.x,这个.firstArea.y,这个.firstArea.w,这个.firstArea.h; this.ctx.fillStyle=红色; this.ctx.fillrecthis.secondArea.x,this.secondArea.y,this.secondArea.w,this.secondArea.h; } } const canvas=新画布; window.onresize=函数{canvas.resize;} 身体{ 填充:0; 保证金:0; } 帆布{ 显示:块; } 观察1:由于resize事件可能以很高的速率触发,因此事件处理程序不应该执行计算代价高昂的操作,例如DOM修改。相反,建议使用requestAnimationFrame、setTimeout或customEvent限制事件 这是从

观察2:在调整画布大小时,需要绑定画布,否则会得到未定义的画布

观察3:调整画布大小时,需要清空元素数组:本例中的this.areasToDraw,并用新元素重新填充数组

我会这样做:

类画布{ 建造师{ this.canvas=document.createElement'canvas'; this.canvas.width=window.innerWidth; this.canvas.height=window.innerHeight; this.ctx=this.canvas.getContext'2d'; document.body.appendChildthis.canvas; this.areasToDraw=[]; //这是一个重要的领域; //这个。调整大小; } 初始区域{ this.firstArea={x:0,y:0,w:this.canvas.width,h:this.canvas.height/2,颜色:绿色} this.areasToDraw.push this.firstArea; this.secondArea={x:0,y:this.firstArea.h,w:this.canvas.width,h:this.canvas.height/2,颜色:红色} this.areasToDraw.push this.secondArea; } 调整大小{ this.canvas.width=window.innerWidth; this.canvas.height=window.innerHeight; //清空数组 this.areasToDraw.length=0; //重新填充数组 这是一个重要的领域; 对于此区域中的此区域,请绘制{ this.ctx.fillStyle=this.areasToDraw[this.areas].color; this.ctx.fillRectthis.areasToDraw[this.areas].x,this.areasToDraw[this.areas].y,this.areasToDraw[this.areas].w,this.areasToDraw[this.areas].h; } } } 让画布=新画布 setTimeoutfunction{ canvas.resize addEventListener'resize',canvas.resize.bindcanvas,false; }, 15; 身体{ 填充:0; 保证金:0; } 帆布{ 显示:块;
}非常感谢!这正是我要找的。