3

Нужно при наведении на соответствующий квадрат отобразить название цвета в рамке (аналог атрибута title в HTML).

Ниже привел код который пока удалось создать:

var ctx = document.getElementById('canvas').getContext('2d');
ctx.fillStyle = "red";
ctx.fillRect(15, 15, 20, 20);
ctx.fillStyle = "blue";
ctx.fillRect(45, 15, 20, 20);
ctx.fillStyle = "green";
ctx.fillRect(75, 15, 20, 20);

document.getElementById('canvas').addEventListener('mousemove', e=>{
  x = e.offsetX; // получаем позицию мыши по координате x
  y = e.offsetY; // получаем позицию мыши по координате y
  ctx.fillStyle = "#333";
  ctx.font = "bold 16px Arial";
  ctx.fillText("Красный", 20, 45);
  ctx.fillText("Синий", 50, 45);
  ctx.fillText("Зеленый", 80, 45);
});
#canvas {
  border: 1px solid #999;
}
<canvas id="canvas" width="110" height="50"></canvas>

1

1 ответ 1

3

Нужно запомнить размеры и координаты квадратов и при движении мыши проверять каждый квадрат на коллизию с координатами курсора.

const ctx = canvas.getContext('2d')
const rs = [
  [15, 15, 20, 20, 'red'],
  [45, 15, 20, 20, 'blue'],
  [75, 15, 20, 20, 'green']
]

drawRect(rs[0]); drawRect(rs[1]); drawRect(rs[2])

function drawRect(r) {
  ctx.fillStyle = r[4]
  ctx.fillRect(...r.slice(0, 4))
}

function drawText(r) {
  ctx.fillStyle = '#333'
  ctx.font = 'bold 16px Arial'
  const w = ctx.measureText(r[4]).width
  ctx.fillText(r[4], r[0] + r[3]/2 - w/2, 47)
}

function rectPointCollision(point, rect) {
  return (
    point[0] > rect[0] && point[0] < rect[0] + rect[2] &&
    point[1] > rect[1] && point[1] < rect[1] + rect[3]
  )
}

canvas.addEventListener('mousemove', e => {
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  
  for (let r of rs) {
    drawRect(r)
    if (rectPointCollision([e.offsetX, e.offsetY], r))
      drawText(r)
  }
})
#canvas {
  border: 1px solid #999;
}
<canvas id="canvas" width="110" height="50"></canvas>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.