javascript 如何为 svg 元素赋予 hsl 颜色值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11257015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:34:16  来源:igfitidea点击:

How to give hsl color value to an svg element

javascriptsvg

提问by A_user

I want to ask that If have read that it is possible to give hsl color value to an svg element.But when I try it like this

我想问一下,如果读过可以为 svg 元素提供 hsl 颜色值。但是当我像这样尝试时

var color = hsl(0, 100%, 50%);

circle.attr("fill" , color);

I got an error "unexpected number"

我收到一个错误“意外的数字”

Can any one guide what is the correct way and also does svg supports all hsl colors

任何人都可以指导什么是正确的方法,并且 svg 是否支持所有 hsl 颜色

Thanks

谢谢

回答by Engineer

Simply

简单地

var color = hsl(0,100%,50%);

line means, that you call hslfunction with 0,100%, 50%parameters, and assign returned value to colorvariable.

line 表示,您hsl使用0, 100%,50%参数调用函数,并将返回值分配给color变量。

You need to use quotes, and pass color as a string:

您需要使用引号,并将颜色作为 a 传递string

 var color = "hsl(0, 100%, 50%)";

 circle.attr("fill" , color);

For more information about HSL, read here.

有关更多信息HSL,请阅读此处

And it doesn't metter whether the hsl color is used by SVG, or by other element. It's just a syntax for specifing color.

并且 hsl 颜色是由SVG还是由其他元素使用并不重要。这只是用于指定color.

UPDATE:To give colorvariable random behavior, try something like this:

更新:要提供color可变随机行为,请尝试以下操作:

var color = "hsl("+[0,0,0].map(function(){   return Math.round(100*Math.random())+"%"; }).join(',')+")";

回答by Sergiu Dumitriu

Well, I don't know if you're using a JavaScript library there, but that doesn't look like valid JS syntax to me. I tried this and it seems to work:

好吧,我不知道您是否在那里使用 JavaScript 库,但这对我来说似乎不是有效的 JS 语法。我试过这个,它似乎工作:

var color = "hsl(0, 100%, 50%)";    // use quotes around the value, since there's no hsl() function
circle.setAttribute("fill", color); // setAttribute(), not attr()
// this also works and is better than setAttribute()
circle.style.fill = "hsl(120, 50%, 50%)";

回答by Malay Sarkar

There is no function called hsl() in Javascript neither fill is an attribute. It's a CSS style. in HTML try it the following way:-

Javascript 中没有名为 hsl() 的函数,fill 也不是属性。这是一种 CSS 样式。在 HTML 中尝试以下方式:-

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
    <circle cx="100" cy="100" r="50" style="fill:hsl(0, 100%, 50%);stroke-width:1;stroke:rgb(0,0,0)" />
</svg>

Also, it seems you are using jQuery or other similar Javascript Library, Thus try the following code:-

此外,您似乎正在使用 jQuery 或其他类似的 Javascript 库,因此请尝试以下代码:-

var color = "hsl(0, 100%, 50%)";
circle.css("fill" , color);