Skip to content Skip to sidebar Skip to footer

Calculate Degrees Of Linear Gradient In Canvas Using Konva With React?

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, whi

Solution 1:

Found the answer on a subreddit for Game Developers /r/gamedev where I shouldn't have asked but I did & it worked.

import { Stage, Layer, Rect } from"react-konva"// linear-gradient(140deg, rgba(165, 142, 251, 1), rgb(233, 191, 248))exportdefaultfunctionApp() {
    const width = window.innerWidth / 1.25// random widthconst height = window.innerHeight / 1.5// random height// Specify angle in degreesconst angleInDeg = 140// Compute angle in radians - CSS starts from 180 degrees and goes clockwise// Math functions start from 0 and go anti-clockwise so we use 180 - angleInDeg to convert between the twoconst angle = ((180 - angleInDeg) / 180) * Math.PI// This computes the length such that the start/stop points will be at the cornersconst length =
        Math.abs(width * Math.sin(angle)) + Math.abs(height * Math.cos(angle))

    // Compute the actual x,y points based on the angle, length of the gradient line and the center of the divconst halfx = (Math.sin(angle) * length) / 2.0const halfy = (Math.cos(angle) * length) / 2.0const cx = width / 2.0const cy = height / 2.0const x1 = cx - halfx
    const y1 = cy - halfy
    const x2 = cx + halfx
    const y2 = cy + halfy

    return (
        <divclassName="App"><h1>Linear Gradient in Konva 👇</h1><Stagewidth={width}height={height}><Layer><Rectname="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><divstyle={{marginTop:10,
                    width,
                    height,
                    backgroundImage: `linear-gradient(${angleInDeg}deg, rgba(165, 142, 251, 1), rgb(233, 191, 248))`,
                }}
            ></div></div>
    )
}

Codesandbox → https://codesandbox.io/s/linear-gradient-in-react-konva-cpgrk?file=/src/App.tsx

Post a Comment for "Calculate Degrees Of Linear Gradient In Canvas Using Konva With React?"