我目前正在學(xué)習(xí) d3,我正在創(chuàng)建一個 SVG,其中有四個矩形,所有矩形都組織在一條水平線上。它們都具有相同的大小、高度和顏色。制作每個rect對象都有很多冗余,我想知道是否有優(yōu)化它的方法。我想知道是否有一種方法可以創(chuàng)建一個rect對象并設(shè)置我需要的幾乎所有屬性(高度、寬度、y 位置、填充顏色),然后進(jìn)入并創(chuàng)建每個矩形的四個副本并只設(shè)置 x-任何我想要的位置。我沒有真正用 JS 編寫過很多代碼,并且習(xí)慣了 Java,所以我對一些對象創(chuàng)建語法和過程并不熟悉。var smallBoxMargin = {top: 20, bottom: 20, left: 20, right: 20}; var boxH = 150; var smallBoxDim = {width: (w/4)-smallBoxMargin.left-smallBoxMargin.right, height: boxH-smallBoxMargin.top-smallBoxMargin.bottom} var boxSvg = d3.select("#boxDiv") .append("svg") .attr("height",boxH) .attr("width",w); var boxMidpoint = w/2; boxSvg.append("rect") //inner left box .attr("class","smallBox") .attr("width",smallBoxDim.width) .attr("height",smallBoxDim.height) .attr("fill",eteOrange) .attr("x", boxMidpoint - smallBoxDim.width - smallBoxMargin.right) .attr("y", smallBoxMargin.top) boxSvg.append("rect") //inner right box .attr("class","smallBox") .attr("width",smallBoxDim.width) .attr("height",smallBoxDim.height) .attr("fill",eteOrange) .attr("x", boxMidpoint+smallBoxMargin.left) .attr("y", smallBoxMargin.top) boxSvg.append("rect") //outer left box .attr("class","smallBox") .attr("width",smallBoxDim.width) .attr("height",smallBoxDim.height) .attr("fill",eteOrange) .attr("x", boxMidpoint-2*smallBoxDim.width - 2*smallBoxMargin.right-smallBoxMargin.left) .attr("y", smallBoxMargin.top) boxSvg.append("rect") //outer right box .attr("class","smallBox") .attr("width",smallBoxDim.width) .attr("height",smallBoxDim.height) .attr("fill",eteOrange) .attr("x", boxMidpoint+smallBoxDim.width+2*smallBoxMargin.left+smallBoxMargin.right) .attr("y", smallBoxMargin.top)上面的代碼有效,它只是在 class、width、height、fill 和 y 的屬性中非常多余。每個boxSvg.append("rect")都是新矩形元素的開始。 smallBoxDim具有較小框的尺寸,具有較小框smallBoxMargin的邊距。
有沒有辦法避免 d3.js 中的代碼重復(fù)?
藍(lán)山帝景
2021-08-20 17:57:11