我有一个填充了对角线图案的 svg 矩形,我想在其上应用渐变。所以渐变应该跨越带有图案的整个矩形,而不应该应用于每个图案项目。
这是我的代码:
import * as React from "react";
import { render } from "react-dom";
const width = 300;
const height = 400;
const patternW = 24;
const patternH = 24;
function createPatternPath(w: number, h: number) {
const diagonal = `M ${0} ${h / 2}, L ${w / 2} ${0},
M ${0} ${h}, L ${w} ${0},
M ${w / 2} ${h}, L ${w} ${h / 2}`;
return diagonal;
}
class App extends React.Component<{}> {
public render() {
return (
<svg width={width + patternW} height={height + patternH}>
<defs>
<linearGradient id="grad" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" stop-color="red"></stop>
<stop offset="100%" stop-color="blue"></stop>
</linearGradient>
<pattern
id="pat"
width={patternW}
height={patternH}
patternUnits="userSpaceOnUse"
>
<path
d={createPatternPath(patternW, patternH)}
fill="transparent"
stroke="url(#grad)"
stroke-width="1"
stroke-linecap="square"
shape-rendering="auto"
/>
</pattern>
<mask id="mask">
<rect width={width} height={height} fill="url(#pat)" />
</mask>
</defs>
<rect
x={0}
y={0}
width={width}
height={height}
//fill="url(#pat)"
//stroke="black"
fill="url(#grad)"
mask="url(#mask)"
/>
</svg>
);
}
}
const rootElement = document.getElementById("root");
render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
结果是:
如您所见,我快到了,我不明白为什么渐变如此苍白,以及为什么每个图案项目的底部比顶部更透明。