使用选择性调色板更改图像一部分的颜色
所以我试图弄清楚如何选择 JPG/SVG 图像的一部分(我正在使用 SVG)并放置一个选择性调色板来用不同的颜色更改每个部分,我进行了搜索,但找不到任何有用的解决方案...我有几个 SVG 图像,我需要一个示例,至少是一个调色板模板。问题是:
- 如何选择图像的 1 部分
- 如何改变图像的一部分的颜色
我需要为可以根据需要更改图像任何部分颜色的用户使用调色板。
这是一个例子
回答
这是一个简单的示例,说明如何选择颜色并使用它来更改 SVG 元素的颜色。代码应该很容易遵循。
let currentSelectedColour = "red";
// For each palette button...
document.querySelectorAll(".palette button").forEach(btn => {
// ... add a click handler that sets the current palette colour
btn.addEventListener("click", evt => {
// 'dataset.colour' is the value of the data-colour attribute.
currentSelectedColour = evt.target.dataset.colour;
// Update the "Current colour is" field to show this colour name
document.getElementById("selectedColour").textContent = currentSelectedColour;
});
});
// For each element in the SVG...
document.querySelectorAll("circle, rect").forEach(shape => {
// ... add a click handler that sets the fill to the current selected colour
shape.addEventListener("click", evt => {
evt.target.setAttribute("fill", currentSelectedColour);
});
});
svg circle,
svg rect {
stroke: black;
}
div {
margin: 3em 0;
}
<svg width="400" viewBox="0 0 400 100">
<circle cx="50" cy="50" r="45" fill="linen"/>
<rect x="110" y="10" width="80" height="80" fill="linen"/>
<circle cx="250" cy="50" r="45" fill="linen"/>
<rect x="310" y="10" width="80" height="80" fill="linen"/>
</svg>
<div>
<button type="button">Red</button>
<button type="button">Orange</button>
<button type="button">Yellow</button>
<button type="button">Green</button>
<button type="button">Blue</button>
<button type="button">Violet</button>
</div>
<div>
Current colour is: <span>red</span>
</div>