简体   繁体   中英

How do I change the css of a rectangle to a gradient in JavaScript?

So basically I'm working on a gradient generator but the gradient just won't appear. I currently have

<rect id="preview" class="preview" width="300" height="50" style="fill:rgb(0,0,0)" />

in the html and

document.getElementById("preview").style.property = "fill: linear-gradient(90deg, rgba(2,0,36,1) 0%, rgba(9,121,103,1) 50%, rgba(0,212,255,1) 100%);"

in the javascript (should give a nice green-to-teal gradient) but it just doesn't work, it shows black and thats it, no idea what to do and how to fix it

As Robert said, for now you need to use SVG <linearGradient> elements.

 document.getElementById("preview").style = "fill: url(#grad);"
 <svg> <defs> <linearGradient id="grad"> <stop offset="0%" stop-color="rgba(2,0,36,1)"/> <stop offset="50%" stop-color="rgba(9,121,103,1)"/> <stop offset="100%" stop-color="rgba(0,212,255,1)"/> </linearGradient> </defs> <rect id="preview" class="preview" width="300" height="50" style="fill:rgb(0,0,0)" /> </svg>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM