[英]How to add color to a path element in an svg dynamically with d3 and react
[英]SVG d3 | can I add inline style dynamically?
我需要動態地為我的SVG添加內聯樣式。 我有1000多個SVG圖表,我必須保存為PNG。 然后,這些將被托管給最終客戶(不允許他們查看圖表背后的完整數據)。 當我轉換圖表時,他們必須保持格式。
SVG將動態添加,我需要為每個添加(相同)樣式聲明。 這是丑陋的,但只是暫時的,直到我生成PNG。 我手動進行內聯樣式/導出工作。
我最近的努力是這樣的:
addStyle(svg);
function addStyle(svg) {
var style = svg.append("style")
.attr("type","text/css")
.attr("float","left");
}
它在注釋中添加了樣式/樣式元素。 它忽略了浮動:左; 我是否將其添加為.attr()或.style()。
編輯:添加CSS代碼。 我需要添加的CSS是圖表:
g.axis path {
fill: none;
stroke: dimgray;
stroke-width: 0.5px;
}
g.axis g.tick line {
stroke: dimgray;
stroke-width: 1px;
}
g.grid g.tick line {
stroke: lightgray;
stroke-width: 0.5px;
}
path.lineF.cons,
path.line.cons {
stroke: white;
fill: none;
stroke-width: 2px;
}
text.import {
fill: #FF376F; /* pink */
}
rect.import {
fill: #FF376F; /* pink */
stroke: white;
stroke-width: 1px;
cursor: pointer;
}
text.export {
fill: #0F86FF;/* blue */
}
rect.export {
fill: #0F86FF;/* blue */
stroke: white;
stroke-width: 1px;
cursor: pointer;
}
rect.prod2.area,
path.area {
fill: #0F86FF;
opacity: 0.8;
}
path.areaF.prod,
rect.prod.area,
path.area.prod {
fill: black;
opacity: 0.4;
}
div.chart {
width: 100%;
}
div.chart svg#svg2 {
width: 100%;
height: 20000px;
}
div.chart svg {
width: 100%;
height: 15000px;
}
text {
fill: dimgray;
/* font-size: 14px; */
font-size: 90%;
/* font-size: 1vw; */
}
text.title {
/* font-size: 20px; */
font-size: 130%;
font-size: 1.4vw;
fill: dimgray;
}
text.titleMain {
fill: white;
font-size: 28px;
/*
font-size: 2.5%;
font-size: 2.5vw;
*/
}
text.label {
font-size: 12px;
}
rect.titleRect {
fill: #1D5185;
}
text.source {
font-size: 9pt;
fill: gainsboro;
font-style: italic;
}
rect.opRate {
fill: black;
opacity: 0.6;
}
path.line.opRate {
stroke: #B7FF0F; /* lime */
stroke-width: 3px;
fill: none;
}
text.opRate {
fill: #B7FF0F;
}
path.arP2 {
stroke-width: 2px;
fill: none;
stroke: black;
}
text.gr0 {
fill: #0F86FF;
}
text.gr2 {
fill: #FF376F;
}
text.gr1 {
fill: #06B04A;
}
path.gr0 {
stroke: #0F86FF;
stroke-width: 2px;
fill: none;
}
path.gr2 {
stroke: #FF376F;
stroke-width: 2px;
fill: none;
}
path.gr1 {
stroke: #06B04A;
stroke-width: 2px;
fill: none;
}
rect.negativeGrowth {
fill: black;
opacity: 0.1;
}
對於表,CSS是這樣的:
text.source {
font-size: 9pt;
fill: gainsboro;
font-style: italic;
}
rect.th {
fill: #0F86FF;
stroke: white;
stroke-width: 1px;
}
rect.td {
stroke: white;
stroke-width: 1px;
fill: #C8E0F9;
}
text.tdLabel {
fill: black;
}
text.th {
fill: white;
}
text.tableTitle {
fill: #1D5185;
font-size: 1.5%;
font-size: 1.5vw;
}
有可能做我想做的事嗎?
svg.append("style").text(cssText)
應該這樣做。 其中cssText是一個包含所有CSS的字符串。
在DOM中創建樣式標記,並將其文本內容設置為您需要的CSS。
並非所有css都適用於SVG元素。 我在這里找到了一個列表: svg上的css樣式 。 我要做的是將每個svg放入它自己的div元素中(你可以在D3中輕松完成),然后設置div元素的樣式。 我發現樣式純粹的html元素比SVG更容易,特別是當有很多時。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.