我想使用JavaScript动态更改图像的颜色。我能够使用JavaScript加载svg路径并更改颜色,但我也想使用更复杂的图像。 (例如,当我动态改变外部图像颜色时,中心椭圆应为黑色。)
这是我更简单的例子:一个缺少洞的椭圆形;我可以在JavaScript中动态地为它着色。
var color = 'red';
var svgSource = "<svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='250' height='150'><path stroke='black' stroke-width='2' fill='" + color + "' d='M 122.55664 14.691406 A 93.393089 51.964569 0 0 0 30.900391 67.289062 A 93.393089 51.964569 0 0 0 124.86133 118.61133 A 93.393089 51.964569 0 0 0 217.67969 66.648438 L 217.65039 65.365234 A 93.393089 51.964569 0 0 0 122.55664 14.691406 z M 91.923828 63.494141 A 47.749851 20.034533 0 0 1 140.54297 83.03125 L 140.55664 83.525391 A 47.749851 20.034533 0 0 1 93.101562 103.56055 A 47.749851 20.034533 0 0 1 45.060547 83.773438 A 47.749851 20.034533 0 0 1 91.923828 63.494141 z' /></svg>";
// display image
document.getElementById("image").innerHTML = "<img src=\"data:image/svg+xml;utf8," + svgSource + "\">";;
<div id="image"></div>
问题:如何通过更复杂的路径执行此操作?
我更复杂的物体由两条路径组成,颜色改变外形:
M 217.67871,66.647797 A 93.393089,51.964569 0 0 1 124.86224,118.61138 93.393089,51.964569 0 0 1 30.899652,67.289449 93.393089,51.964569 0 0 1 122.55587,14.692141 93.393089,51.964569 0 0 1 217.65023,65.364589
由
定义的实心黑色内椭圆M 140.55713,83.526031 A 47.749851,20.034533 0 0 1 93.102092,103.56018 47.749851,20.034533 0 0 1 45.061071,83.773416 47.749851,20.034533 0 0 1 91.922895,63.494936 47.749851,20.034533 0 0 1 140.54257,83.031301
答案 0 :(得分:1)
如果将两个形状组合成一个路径,则不会有两个填充形状。通常情况下,最终会形成一个带孔的形状。而你将无法改变洞的颜色。
您需要做的是有两个单独的<path>
元素
答案 1 :(得分:1)
我最终使用svg
标签进行了充分的实验,并想出了如何将内圈作为不同的颜色。我以为我的svg
标签中需要两个路径元素(@Paul LeBeau是正确的),但我一直搞乱语法。每个path
都应该在它自己的尖括号中:
var svgSource = "<svg ... ><path ... /><path ... /></svg>"
完整的工作示例:
var color = 'red',
color2 = 'black';
var svgSource = "<svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='250' height='150'>"
+ "<path stroke='black' stroke-width='2' fill='" + color
+ "' d='M 122.55664 14.691406 A 93.393089 51.964569 0 0 0 30.900391 67.289062 A 93.393089 51.964569 0 0 0 124.86133 118.61133 A 93.393089 51.964569 0 0 0 217.67969 66.648438 L 217.65039 65.365234 A 93.393089 51.964569 0 0 0 122.55664 14.691406 z' />"
+ "<path stroke='black' stroke-width='2' fill='" + color2
+ "' d='M 91.923828 63.494141 A 47.749851 20.034533 0 0 1 140.54297 83.03125 L 140.55664 83.525391 A 47.749851 20.034533 0 0 1 93.101562 103.56055 A 47.749851 20.034533 0 0 1 45.060547 83.773438 A 47.749851 20.034533 0 0 1 91.923828 63.494141 z' />"
+ "</svg>";
// display image
document.getElementById("image").innerHTML = "<img src=\"data:image/svg+xml;utf8," + svgSource + "\">";;
<div id="image"></div>
请注意,为了便于阅读,我将svgSource
变量分解为多个字符串,因为我添加了几个不同颜色的图标,因此我的颜色变量发生了变化。如果您不想动态添加颜色,<svg>
只能写成一个长字符串。