I want to calculate the degree used in a Linear Gradient β linear-gradient(140deg, rgba(165, 142, 251, 1), rgb(233, 191, 248))
into x
& y
co-ordinates to use it in Konva, which is basically a wrapper around Canvas.
I have found quite similar questions with a caveat that they are answered in vanilla Canvas, not Konva like:
https://mcmap.net/q/1174733/-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
But when I tried implementing them, I don't get the same desired effect as I get in CSS (see the comparison):
The code is quite similar to what is posted in some of the answers above:
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>
)
}
I think the error is in length
as I don't know what it should be it's certainly not clear. Also, not sure about the x1
& y1
co-ordinates as I think they should be zero & hence, can be removed.
How do I get the same effect?
Codesandbox β https://codesandbox.io/s/linear-gradient-in-react-konva-cpgrk?file=/src/App.tsx