亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有沒有辦法避免 d3.js 中的代碼重復?

有沒有辦法避免 d3.js 中的代碼重復?

藍山帝景 2021-08-20 17:57:11
我目前正在學習 d3,我正在創建一個 SVG,其中有四個矩形,所有矩形都組織在一條水平線上。它們都具有相同的大小、高度和顏色。制作每個rect對象都有很多冗余,我想知道是否有優化它的方法。我想知道是否有一種方法可以創建一個rect對象并設置我需要的幾乎所有屬性(高度、寬度、y 位置、填充顏色),然后進入并創建每個矩形的四個副本并只設置 x-任何我想要的位置。我沒有真正用 JS 編寫過很多代碼,并且習慣了 Java,所以我對一些對象創建語法和過程并不熟悉。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的邊距。
查看完整描述

2 回答

  • 2 回答
  • 0 關注
  • 206 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號