首页 > 解决方案 > 红点跟随鼠标并在图案周围移动

问题描述

我需要编写一个 JS 函数来负责移动鼠标光标后面的红点。点应该沿着闪电轮廓移动,并且仅在检测到黑色(我们的轮廓)时移动,当鼠标光标碰到不同的颜色(离开轮廓)时,点返回到其初始位置。

我有功能,但它不起作用。我不知道为什么,我不知道我应该怎么做才能修复它。

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

const image = new Image();
image.addEventListener("load", (e) => {
  ctx.drawImage(image, 0, 0);
});
image.src = "https://frontdevhero.pl/api/assets/thunder.png";


function redDot() {

  ctx.beginPath();
  ctx.arc(312, 220, 10, 0, angleToRadian(360));
  ctx.fillStyle = "#7c0202";
  ctx.fill();
  ctx.stroke;
  ctx.closePath();
}

setInterval(redDot, 10);

const angleToRadian = function(angle) {

  return (Math.PI / 180) * angle;
};
let i = 0;
let start;
let back;

redDot.style.left = `${e.offsetX}px`;
redDot.style.top = `${e.offsetY}px`;

function redDotGo() {
  redDot.style.left = `${e.offsetX[i + 1]}px`;
  redDot.style.top = `${e.offsetY[i + 1]}px`;
}

function redDotBack() {
  redDot.style.left = `${e.offsetX[i - 1]}px`;
  redDot.style.top = `${e.offsetY[i - 1]}px`;
}

function moveRedDot() {
  clearInterval(back);
  redDotGo();
  i++;
  start = setInterval(() => {
    redDotGo();
    i++;
  }, 1000);
}

function mouseOut() {
  clearInterval(start);
  reddotBack;
  i--;
  back = setInterval(() => {
    reddotBack();
    i--;
  }, 1000);
}

function mousemove() {
  var curleft = 312,
    curtop = 220;
  if (r == 0 || g == 0 || b == 0) {
    moveRedDot;
  } else {
    mouseOut;
  }
}

redDot.addEventListener("mouseover", moveRedDot);
redDot.addEventListener("mouseout", mouseOut);
<canvas id="canvas" width="1200" height="800">
        <div id="reddot"></div> 
    </canvas>
<div id="status"></div><br>
<div id="color" style="width:30px;height:30px;"></div>
x:<span id="posX">0</span>px y:<span id="posY">0</span>px

<p>Follow the mouse over the thunder!</p>

标签: javascripthtmlcss

解决方案


推荐阅读