gpt4 book ai didi

javascript - 将背景添加到 svg 折线

转载 作者:太空宇宙 更新时间:2023-11-04 02:07:45 29 4
gpt4 key购买 nike

我正在尝试向 svg 多段线添加类似叠加的效果。基本目标是使单击该线变得容易,并且由于该线太细,我想添加一个背景叠加层,当鼠标悬停在上面时会亮起。

我使用多边形尝试了以下方法,但这看起来很乏味。 (线总是由 3 段组成)

是否有更复杂的方法来实现目标。

或者是否有更好的方法使该行更易于点击?

function draw(x1, y1, x2, y2) {

var svg = d3.select("#canvas");

var overlay = svg.append("polygon")
.style("fill", "yellow")
.style("opacity", "0")
.attr("points", function() {
var s = 5,
h = 20;
var p1 = [x1, y1 - s],
p2 = [x1 + h + s, y1 - s],
p3 = [x2 - h + s, y2 - s],
p4 = [x2, y2 - s],
p5 = [x2, y2 + s],
p6 = [x2 - h - s, y2 + s],
p7 = [x1 + h - s, y1 + s],
p8 = [x1, y1 + s];
return p1 + " " + p2 + " " + p3 + " " + p4 + " " + p5 + " " + p6 + " " + p7 + " " + p8;
})
.on("mouseover", function() {
d3.select(this).style("opacity", "0.5");
})
.on("mouseleave", function() {
d3.select(this).style("opacity", "0");
});
var line = svg.append("polyline")
.style("fill", "none")
.style("stroke", "black")
.attr("points", function() {
var margin = 20;
var p1 = [x1, y1],
p2 = [x1 + margin, y1],
p3 = [x2 - margin, y2],
p4 = [x2, y2];

return p1 + " " + p2 + " " + p3 + " " + p4;
});

}
draw(10, 10, 200, 200);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.js"></script>
<svg height="250" width="500" id="canvas">


</svg>

最佳答案

你不能插入另一行不透明度为零的事件吗?像这样:

function draw(x1, y1, x2, y2) {

var svg = d3.select("#canvas");

/* var overlay = svg.append("polygon")
.style("fill", "yellow")
.attr("points", function() {
var s = 5,
h = 20;
var p1 = [x1, y1 - s],
p2 = [x1 + h + s, y1 - s],
p3 = [x2 - h + s, y2 - s],
p4 = [x2, y2 - s],
p5 = [x2, y2 + s],
p6 = [x2 - h - s, y2 + s],
p7 = [x1 + h - s, y1 + s],
p8 = [x1, y1 + s];
return p1 + " " + p2 + " " + p3 + " " + p4 + " " + p5 + " " + p6 + " " + p7 + " " + p8;
});
*/

var lineBackround = svg.append("polyline")
.style("fill", "none")
.style("stroke", "yellow")
.style('stroke-width',5)
.style('opacity', 0)//change this to 0 to not see it
.attr("points", function() {
var margin = 20;
var p1 = [x1, y1],
p2 = [x1 + margin, y1],
p3 = [x2 - margin, y2],
p4 = [x2, y2];

return p1 + " " + p2 + " " + p3 + " " + p4;
})
.on('mouseover', function(){
d3.select(this).style('opacity',1);
//alert('over')
})
.on('mouseout', function(){
d3.select(this).style('opacity',0);
//alert('over')
})


var line = svg.append("polyline")
.style("fill", "none")
.style("stroke", "black")
.attr("points", function() {
var margin = 20;
var p1 = [x1, y1],
p2 = [x1 + margin, y1],
p3 = [x2 - margin, y2],
p4 = [x2, y2];

return p1 + " " + p2 + " " + p3 + " " + p4;
})





}
draw(10, 10, 200, 200);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.js"></script>
<svg height="250" width="500" id="canvas">


</svg>

关于javascript - 将背景添加到 svg 折线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40397945/

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