[英]How to give SVG circle a stroke according to the values from database?
无需使用更高级的代码(但更简单地创建“甜甜圈”弧,例如使用 D3.js 库等),您可以使用 javascript 和基本 SVG 解决此问题:
<?php
$total_hours = 10;
$used_hours = 4;
$remaining_hours = 6;
?>
<svg height="100" width="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="3"
fill="transparent" />
<circle cx="50" cy="50" r="40" stroke="red" stroke-width="3"
fill="transparent" />
</svg>
<script>
var path = document.getElementsByTagName("circle")[1];
var length = path.getTotalLength();
var total_hours = <?php echo $total_hours ?>;
var used_hours = <?php echo $used_hours ?>;
var remaining_hours = <?php echo $remaining_hours ?>;
var ratio = used_hours/total_hours;
var used_path_length = (1-ratio) * length;
path.setAttribute("style", "stroke-dasharray: " + length + "; stroke-dashoffset: " + used_path_length);
path.setAttribute("transform", "rotate(-90, 50, 50)");
</script>
红色圆圈绘制在绿色顶部(SVG 没有 z-index 作为 HTML5 DOM,例如最后绘制的内容放在所有先前对象的顶部)。 然后根据您的变量调整其(描边)路径长度。
为清楚起见,只需拥有总小时数和使用小时数(作为变量)就足够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.