【发布时间】:2021-07-24 13:16:38
【问题描述】:
我想计算线性渐变中使用的度数 → linear-gradient(140deg, rgba(165, 142, 251, 1), rgb(233, 191, 248)) 到 x 和 y 坐标中,以便在 Konva 中使用它,它基本上是 Canvas 的包装器。
我发现了非常相似的问题,但需要注意的是,它们是在 vanilla Canvas 中回答的,而不是像 Konva 这样的:
https://stackoverflow.com/questions/37669239/how-can-i-rotate-a-linear-gradient- CSS convert gradient to the canvas version
- Canvas to use liniear gradient background set with an angle
- Calculate rotation of canvas gradient
但是当我尝试实现它们时,我没有得到与 CSS 相同的预期效果(参见比较):
代码与上面一些答案中发布的非常相似:
import { Stage, Layer, Rect } from "react-konva"
// linear-gradient(140deg, rgba(165, 142, 251, 1), rgb(233, 191, 248))
export default function App() {
const width = window.innerWidth / 1.25 // random width
const height = window.innerHeight / 1.5 // random height
const x1 = 0
const y1 = 0
const angle = (140 / 180) * Math.PI
const length = width
const x2 = x1 + Math.cos(angle) * length
const y2 = y1 + Math.sin(angle) * length
return (
<div className="App">
<h1>Linear Gradient in Konva ????</h1>
<Stage width={width} height={height}>
<Layer>
<Rect
name="transparentBackground"
width={width}
height={height}
x={0}
y={0}
fillPriority="linear-gradient" // 'color', 'pattern', 'linear-gradient', 'radial-gradient'
/* linear-gradient */
fillLinearGradientStartPoint={{ x: x1, y: y1 }}
fillLinearGradientEndPoint={{ x: x2, y: y2 }}
fillLinearGradientColorStops={[
0,
"rgba(165, 142, 251, 1)",
1,
"rgb(233, 191, 248)",
]}
/>
</Layer>
</Stage>
<h1>CSS Gradient ????</h1>
<div
style={{
marginTop: 10,
width,
height,
backgroundImage:
"linear-gradient(140deg, rgba(165, 142, 251, 1), rgb(233, 191, 248))",
}}
></div>
</div>
)
}
我认为错误在length,因为我不知道应该是什么,当然也不清楚。另外,不确定x1 和y1 坐标,因为我认为它们应该为零,因此可以删除。
我怎样才能得到同样的效果?
代码沙盒 → https://codesandbox.io/s/linear-gradient-in-react-konva-cpgrk?file=/src/App.tsx
【问题讨论】:
标签: javascript css canvas konvajs react-konva