gpt4 book ai didi

javascript - 缩放 SVG 路径的填充部分

转载 作者:行者123 更新时间:2023-12-01 23:22:21 24 4
gpt4 key购买 nike

假设我们有以下 SVG 路径:

<path id="heart" d="M 10,30 A 20,20 0,0,1 50,30 A 20,20 0,0,1 90,30 Q 90,60 50,90 Q 10,60 10,30 z" />

我想知道是否有一种方法可以只填充与给定比例成比例的此形状的一部分区域。我确实需要为等于比率的像素数量上色。

例如,比率 = 0,6,则只需填充形状的 60% 像素(从底部开始)。

编辑:

我试图在评论中实现@RobertLongson 的提示。给你:

<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">

<linearGradient id="myGradient" gradientTransform="rotate(90)">
<stop offset="50%" stop-color="black" stop-opacity='0' />
<stop offset="50%" stop-color="black" />
</linearGradient>


<path id="heart" d="M 10,30 A 20,20 0,0,1 50,30 A 20,20 0,0,1 90,30 Q 90,60 50,90 Q 10,60 10,30 z" fill="url('#myGradient')" stroke="black" stroke-width="1" />
</svg>

但是,如果比率为 50%,则此方法无效。 (即我们没有为 50% 的像素着色)

最佳答案

How to fill a <path> with a percentage volume

我最终选择了蛮力方法;

检查每个 SVG 像素是否在 isPointInFill 的形状中

所有数据都在 filled 中可用数组和 P.y值(value)观

filled值是从路径形状的底部顶部

需要更多地使用这些值来绘制实心填充或渐变

50%、20% 和 80% <svg-area>形状:

<style>
svg { --size: 180px; height: var(--size); background: pink }
path { fill: lightgreen; stroke: grey }
</style>
<svg-area percent=".5">
<svg viewBox="0 0 100 100">
<path d="M10,30A20,20,0,0,1,50,30A20,20,0,0,1,90,30Q90,60,50,90Q10,60,10,30z"></path>
</svg>
</svg-area>
<svg-area percent=".2">
<svg viewBox="0 0 100 100">
<path d="M60,10L90,90L10,60z"></path>
</svg>
</svg-area>
<svg-area percent=".8">
<svg viewBox="0 0 50 50">
<path d="m18 15q41 18 28-8l-14 30-29-15a1 1 0 0029 15z"></path>
</svg>
</svg-area>
<script>
customElements.define("svg-area", class extends HTMLElement {
connectedCallback() {
setTimeout(() => {// make sure Web Component can read parsed innerHTML
let svg = this.querySelector("svg");
let path = svg.querySelector("path");
let filled = [], percent = this.getAttribute("percent");
Array(svg.height.baseVal.value).fill().map((_, y) => {
Array(svg.width.baseVal.value).fill().map((_, x) => {
let P = svg.createSVGPoint(); P.x = x; P.y = y;
if (path.isPointInFill(P)) filled.push( P );
});
});
svg.append(
...filled.reverse()
.filter( (P,idx) => idx < filled.length * percent)
.map( P => this.circle(P.x, P.y, "green") ));
});
}
circle(cx, cy, fill) {
let circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.setAttribute("cx", cx);
circle.setAttribute("cy", cy);
circle.setAttribute("fill", fill);
circle.setAttribute("r", .3);
return circle;
}
});
</script>

关于javascript - 缩放 SVG 路径的填充部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67873157/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com