gpt4 book ai didi

javascript - Bresenham 的线条绘制算法来突出显示框

转载 作者:行者123 更新时间:2023-11-28 04:45:21 24 4
gpt4 key购买 nike

我正在寻找这种行为 http://www.brainjunkie.com/web/js-wordsearch/但有了这个盒子:

div {
display: inline-block;
width: 100px;
height: 100px;
border: 1px solid black;
cursor: pointer;
}

div.selected,
div:hover {
background-color: red;
color: white;
}
<div>A</div>
<div>B</div>
<div>C</div>

我希望能够单击一个框,然后拖动并更改其他两个框的颜色。

我已经发表过一篇文章,但接受答案(我没有意识到我接受时对我来说效果不佳,因为我正在寻找上面链接中的确切行为。

谢谢。

最佳答案

For Bresenham’s Line Generation
Assumptions :
1) Line is drawn from left to right.
2) x1 < x2 and y1< y2
3) Slope of the line is between 0 and 1.
We draw a line from lower left to upper
right.

var x1, y1, x2, y2;
function handleMouseDown(e){
x1 = +e.target.dataset.x;
y1 = +e.target.dataset.y;

container.addEventListener('mousemove', handleMouseMove);
e.preventDefault();
}
function handleMouseMove(e){
x2 = +e.target.dataset.x;
y2 = +e.target.dataset.y;

var ele = document.querySelectorAll('[data-x][data-y]');
ele.forEach(function(val){
val.classList.remove('selected')
});

bresenham(x1, y1, x2, y2);


}
function handleMouseUp(e){
var ele = document.querySelectorAll('[data-x][data-y]');
ele.forEach(function(val){
val.classList.remove('selected')
});
e.preventDefault();
container.removeEventListener('mousemove', handleMouseMove);
}
function bresenham(x1 , y1, x2 , y2){

var m_new = 2 * (y2 - y1);
var slope_error_new = m_new - (x2 - x1);
for (var x = x1, y = y1; x <= x2; x++)
{
var ele = document.querySelector('[data-x="'+x+'"][data-y="'+y+'"]');
ele.classList.add('selected');
// Add slope to increment angle formed
slope_error_new += m_new;

// Slope error reached limit, time to
// increment y and update slope error.
if (slope_error_new >= 0)
{
y++;
slope_error_new -= 2 * (x2 - x1);
}
}
}
var container = document.getElementById('container');
container.addEventListener('mousedown', handleMouseDown);
container.addEventListener('mouseup', handleMouseUp);
div {
display: inline-block;
width: 100px;
height: 100px;
border: 1px solid black;
cursor: pointer;
}

div.selected{
background-color: red;
color: white;
}
<span id="container">
<div data-x="0" data-y="0" >A</div>
<div data-x="1" data-y="0" >B</div>
<div data-x="2" data-y="0" >C</div>
</span>

关于javascript - Bresenham 的线条绘制算法来突出显示框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43431089/

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