Javascript 事件侦听器和数组

Javascript event listeners and arrays

我正在尝试用 3 个按钮触发的数组中的 3 个图像重新创建从刮擦到显示图像的效果。我的事件侦听器不工作,如您所见,无论按钮如何,它都显示相同的显示图像。事件侦听器语法让我有点困惑,我希望得到一些具体的帮助。

素描图像叠加层始终相同。你能指导我哪里出错了吗?

代码很多,很抱歉,但我认为最好把所有的细节都写进去。提前谢谢你!

const imgArr = [{
    sketch: 'https://trellidor.co.za/wp-content/uploads/2020/12/Sketch.png',
    background1: 'https://images.pexels.com/photos/1666012/pexels-photo-1666012.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500'
  },
  {
    sketch: 'https://trellidor.co.za/wp-content/uploads/2020/12/Sketch.png',
    background2: 'https://images.pexels.com/photos/572897/pexels-photo-572897.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500'
  },
  {
    sketch: 'https://trellidor.co.za/wp-content/uploads/2020/12/Sketch.png',
    background3: 'https://images.pexels.com/photos/2365457/pexels-photo-2365457.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500'
  },
]

const btn = document.querySelector('#special'),
  bridge = document.querySelector("#bridge"),
  bridgeCanvas = bridge.getContext('2d'),
  brushRadius = (bridge.width / 100) * 7;

// default image
img = new Image();
img.onload = function() {
  bridgeCanvas.drawImage(img, 0, 0, bridge.width, bridge.height);
}
img.src = 'https://trellidor.co.za/wp-content/uploads/2020/12/Sketch.png'


btn.addEventListener('click', () => {
  img.src = imgArr[background1].sketch
  bridge.style.background1 = `url(${imgArr[background1].background1})`;
  bridge.style.backgroundSize = 'cover';
  bridgeCanvas.clearRect(0, 0, bridge.width, bridge.height);
  bridgeCanvas.globalCompositeOperation = "destination-over";
})

btn.addEventListener('click', () => {
  img.src = imgArr[background2].sketch
  bridge.style.background2 = `url(${imgArr[background2].background2})`;
  bridge.style.backgroundSize = 'cover';
  bridgeCanvas.clearRect(0, 0, bridge.width, bridge.height);
  bridgeCanvas.globalCompositeOperation = "destination-over";
})

function getBrushPos(xRef, yRef) {
  const bridgeRect = bridge.getBoundingClientRect();
  return {
    x: Math.floor((xRef - bridgeRect.left) / (bridgeRect.right - bridgeRect.left) * bridge.width),
    y: Math.floor((yRef - bridgeRect.top) / (bridgeRect.bottom - bridgeRect.top) * bridge.height)
  };
}

function drawDot(mouseX, mouseY) {
  bridgeCanvas.beginPath();
  bridgeCanvas.arc(mouseX, mouseY, brushRadius, 0, 2 * Math.PI, true);
  bridgeCanvas.globalCompositeOperation = "destination-out";
  bridgeCanvas.fill();
}


bridge.addEventListener("mousemove", (e) => {
  let brushPos = getBrushPos(e.clientX, e.clientY);
  if (e.which === 1) {
    drawDot(brushPos.x, brushPos.y);
  }
}, false);

bridge.addEventListener("touchmove", function(e) {
  let touch = e.targetTouches[0];
  if (touch) {
    let brushPos = getBrushPos(touch.pageX, touch.pageY);
    drawDot(brushPos.x, brushPos.y);
  }
}, false);
body {
  margin: 0;
}

#bridge {
  margin: 0 auto;
  background-image: url('https://trellidor.co.za/wp-content/uploads/2020/12/Colour.png');
  background-image: -webkit-image-set(url('https://trellidor.co.za/wp-content/uploads/2020/12/Colour.png') 2x);
  background-size: cover;
  width: 100%;
  max-width: 750px;
  height: auto;
  cursor: crosshair;
  cursor: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/circular-cursor.png') 53 53, crosshair;
}

#bridgeContainer {
  text-align: center;
  font-family: Avenir, sans-serif;
}

#bridgeContainer figcaption {
  margin-top: 2rem;
}

#special {
  background-color: blue;
  color: white;
  border: none;
  outline: none;
  border-radius: 1.5rem;
  font-size: larger;
  padding: .5rem 1rem;
}

#special2 {
  background-color: blue;
  color: white;
  border: none;
  outline: none;
  border-radius: 1.5rem;
  font-size: larger;
  padding: .5rem 1rem;
}

#special3 {
  background-color: blue;
  color: white;
  border: none;
  outline: none;
  border-radius: 1.5rem;
  font-size: larger;
  padding: .5rem 1rem;
}
<figure id="bridgeContainer">
  <canvas id="bridge" width="750" height="465"></canvas>
</figure>
<button id="special">Color1</button>
<button id="special2">Color2</button>
<button id="special3">Color3</button>

您的代码中存在多个错误。首先,您尝试访问未定义 background1 的 imgArr[background1] 。相反,您应该尝试按索引访问,例如 0,1,2。您没有其他 2 个按钮的任何事件侦听器。最后一件事是不要将新图像分配给 bridge.style.background1,而应将它们分配给 bridge.style.background。您的素描图像是相同的,因为在 imgArr 中所有素描图像都是相同的 sketch: 'https://trellidor.co.za/wp-content/uploads/2020/12/Sketch.png'。试试下面的代码片段。

const imgArr = [{
    sketch: 'https://trellidor.co.za/wp-content/uploads/2020/12/Sketch.png',
    background1: 'https://images.pexels.com/photos/1666012/pexels-photo-1666012.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500'
  },
  {
    sketch: 'https://trellidor.co.za/wp-content/uploads/2020/12/Sketch.png',
    background2: 'https://images.pexels.com/photos/572897/pexels-photo-572897.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500'
  },
  {
    sketch: 'https://trellidor.co.za/wp-content/uploads/2020/12/Sketch.png',
    background3: 'https://images.pexels.com/photos/2365457/pexels-photo-2365457.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500'
  },
]

const btn = document.querySelector('#special'),
btn1 = document.querySelector('#special2'),
btn2 = document.querySelector('#special3')
  bridge = document.querySelector("#bridge"),
  bridgeCanvas = bridge.getContext('2d'),
  brushRadius = (bridge.width / 100) * 7;

// default image
img = new Image();
img.onload = function() {
  bridgeCanvas.drawImage(img, 0, 0, bridge.width, bridge.height);
}
img.src = 'https://trellidor.co.za/wp-content/uploads/2020/12/Sketch.png'


btn.addEventListener('click', () => {
  img.src = imgArr[0].sketch
  bridge.style.background = `url(${imgArr[0].background1})`;
  bridge.style.backgroundSize = 'cover';
  bridgeCanvas.clearRect(0, 0, bridge.width, bridge.height);
  bridgeCanvas.globalCompositeOperation = "destination-over";
})

btn1.addEventListener('click', () => {
  img.src = imgArr[1].sketch
  bridge.style.background = `url(${imgArr[1].background2})`;
  bridge.style.backgroundSize = 'cover';
  bridgeCanvas.clearRect(0, 0, bridge.width, bridge.height);
  bridgeCanvas.globalCompositeOperation = "destination-over";
})

btn2.addEventListener('click', () => {
  img.src = imgArr[2].sketch
  bridge.style.background = `url(${imgArr[2].background3})`;
  bridge.style.backgroundSize = 'cover';
  bridgeCanvas.clearRect(0, 0, bridge.width, bridge.height);
  bridgeCanvas.globalCompositeOperation = "destination-over";
})

function getBrushPos(xRef, yRef) {
  const bridgeRect = bridge.getBoundingClientRect();
  return {
    x: Math.floor((xRef - bridgeRect.left) / (bridgeRect.right - bridgeRect.left) * bridge.width),
    y: Math.floor((yRef - bridgeRect.top) / (bridgeRect.bottom - bridgeRect.top) * bridge.height)
  };
}

function drawDot(mouseX, mouseY) {
  bridgeCanvas.beginPath();
  bridgeCanvas.arc(mouseX, mouseY, brushRadius, 0, 2 * Math.PI, true);
  bridgeCanvas.globalCompositeOperation = "destination-out";
  bridgeCanvas.fill();
}


bridge.addEventListener("mousemove", (e) => {
  let brushPos = getBrushPos(e.clientX, e.clientY);
  if (e.which === 1) {
    drawDot(brushPos.x, brushPos.y);
  }
}, false);

bridge.addEventListener("touchmove", function(e) {
  let touch = e.targetTouches[0];
  if (touch) {
    let brushPos = getBrushPos(touch.pageX, touch.pageY);
    drawDot(brushPos.x, brushPos.y);
  }
}, false);
body {
  margin: 0;
}

#bridge {
  margin: 0 auto;
  background-image: url('https://trellidor.co.za/wp-content/uploads/2020/12/Colour.png');
  background-image: -webkit-image-set(url('https://trellidor.co.za/wp-content/uploads/2020/12/Colour.png') 2x);
  background-size: cover;
  width: 100%;
  max-width: 750px;
  height: auto;
  cursor: crosshair;
  cursor: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/circular-cursor.png') 53 53, crosshair;
}

#bridgeContainer {
  text-align: center;
  font-family: Avenir, sans-serif;
}

#bridgeContainer figcaption {
  margin-top: 2rem;
}

#special {
  background-color: blue;
  color: white;
  border: none;
  outline: none;
  border-radius: 1.5rem;
  font-size: larger;
  padding: .5rem 1rem;
}

#special2 {
  background-color: blue;
  color: white;
  border: none;
  outline: none;
  border-radius: 1.5rem;
  font-size: larger;
  padding: .5rem 1rem;
}

#special3 {
  background-color: blue;
  color: white;
  border: none;
  outline: none;
  border-radius: 1.5rem;
  font-size: larger;
  padding: .5rem 1rem;
}
<figure id="bridgeContainer">
  <canvas id="bridge" width="750" height="465"></canvas>
</figure>
<button id="special">Color1</button>
<button id="special2">Color2</button>
<button id="special3">Color3</button>

看看我在 EventListener 中所做的更改。

我所做的修改是: 在按钮上添加 class 以便可以一起选择它们。当为循环放置监听器时,还会在按钮上放置“日期”信息。该信息是一个序列号,对应Array记录

const imgArr = [{
    sketch: 'https://trellidor.co.za/wp-content/uploads/2020/12/Sketch.png',
    background: 'https://images.pexels.com/photos/1666012/pexels-photo-1666012.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500'
},
{
    sketch: 'https://trellidor.co.za/wp-content/uploads/2020/12/Sketch.png',
    background: 'https://images.pexels.com/photos/572897/pexels-photo-572897.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500'
},
{
    sketch: 'https://trellidor.co.za/wp-content/uploads/2020/12/Sketch.png',
    background: 'https://images.pexels.com/photos/2365457/pexels-photo-2365457.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500'
},
]

const btn = document.querySelectorAll('.special'),
    bridge = document.querySelector("#bridge"),
    bridgeCanvas = bridge.getContext('2d'),
    brushRadius = (bridge.width / 100) * 7;

// default image
img = new Image();
img.onload = function () {
    bridgeCanvas.drawImage(img, 0, 0, bridge.width, bridge.height);
}
img.src = 'https://trellidor.co.za/wp-content/uploads/2020/12/Sketch.png'


for (var i = 0; i < imgArr.length; i++) {
    btn[i].setAttribute('data', i);
    btn[i].addEventListener("click", function () {
        myFunc(this);
    });
}

function myFunc(x) {
    var arr = x.getAttribute('data');
    img.src = imgArr[arr].sketch
    bridge.style.background = `url(${imgArr[arr].background})`;
    bridge.style.backgroundSize = 'cover';
    bridgeCanvas.clearRect(0, 0, bridge.width, bridge.height);
    bridgeCanvas.globalCompositeOperation = "destination-over";
}

function getBrushPos(xRef, yRef) {
    const bridgeRect = bridge.getBoundingClientRect();
    return {
        x: Math.floor((xRef - bridgeRect.left) / (bridgeRect.right - bridgeRect.left) * bridge.width),
        y: Math.floor((yRef - bridgeRect.top) / (bridgeRect.bottom - bridgeRect.top) * bridge.height)
    };
}

function drawDot(mouseX, mouseY) {
    bridgeCanvas.beginPath();
    bridgeCanvas.arc(mouseX, mouseY, brushRadius, 0, 2 * Math.PI, true);
    bridgeCanvas.globalCompositeOperation = "destination-out";
    bridgeCanvas.fill();
}


bridge.addEventListener("mousemove", (e) => {
    let brushPos = getBrushPos(e.clientX, e.clientY);
    if (e.which === 1) {
        drawDot(brushPos.x, brushPos.y);
    }
}, false);

bridge.addEventListener("touchmove", function (e) {
    let touch = e.targetTouches[0];
    if (touch) {
        let brushPos = getBrushPos(touch.pageX, touch.pageY);
        drawDot(brushPos.x, brushPos.y);
    }
}, false);
body {
    margin: 0;
}

#bridge {
    margin: 0 auto;
    background-image: url('https://trellidor.co.za/wp-content/uploads/2020/12/Colour.png');
    background-image: -webkit-image-set(url('https://trellidor.co.za/wp-content/uploads/2020/12/Colour.png') 2x);
    background-size: cover;
    width: 100%;
    max-width: 750px;
    height: auto;
    cursor: crosshair;
    cursor: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/circular-cursor.png') 53 53, crosshair;
}

#bridgeContainer {
    text-align: center;
    font-family: Avenir, sans-serif;
}

#bridgeContainer figcaption {
    margin-top: 2rem;
}

#special {
    background-color: blue;
    color: white;
    border: none;
    outline: none;
    border-radius: 1.5rem;
    font-size: larger;
    padding: .5rem 1rem;
}

#special2 {
    background-color: blue;
    color: white;
    border: none;
    outline: none;
    border-radius: 1.5rem;
    font-size: larger;
    padding: .5rem 1rem;
}

#special3 {
    background-color: blue;
    color: white;
    border: none;
    outline: none;
    border-radius: 1.5rem;
    font-size: larger;
    padding: .5rem 1rem;
}
<figure id="bridgeContainer">
    <canvas id="bridge" width="750" height="465"></canvas>
</figure>
<button id="special" class="special">Color1</button>
<button id="special2" class="special">Color2</button>
<button id="special3" class="special">Color3</button>