Показать подсказку с помощью JavaScript - PullRequest
1 голос
/ 24 октября 2019

Я пытаюсь показать всплывающую подсказку, наведя указатель мыши на круг внутри холста. В то время как CSS изменяется от скрытого к видимому с помощью javaScript (увидел, что с помощью chrome inspect), всплывающая подсказка не отображается. Пожалуйста, помогите разобраться с этим. Спасибо за вашу помощь.

const canvas = document.getElementById('flower');
const ctx = canvas.getContext('2d');

const circle2 = new Path2D();
                        circle2.arc(100, 100, 25, 0, 2 * Math.PI);
                        ctx.fillStyle = "red";
                        ctx.fill(circle2);
                        
canvas.addEventListener("mousemove", function(event2) {
                            if (ctx.isPointInPath(circle2, event2.clientX, event2.clientY)) {
                                showtext();
                            }
                        }); 
                        
function showtext(){
    document.getElementById("tooltiptext").style.visibility = 'visible';
}
html, body, div, canvas {
        width:  100%;
        height: 100%;
        margin: 0;
}
    .tooltip {
        position: relative;
        display: inline-block;
        border-bottom: 1px dotted black; 
    }
    .tooltip .tooltiptextstyle {
        visibility: hidden; 
        display: block;
        width: 120px;
        background-color: black;
        color: #fff;
        text-align: center;
        padding: 5px 0;
        border-radius: 6px;
        position: absolute;
        z-index: 1;
    }
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link type="text/css" href="style.css"/>
    <script type="text/typescript" src="main.ts"></script>
</head>
<body>
    <div id="design" class="design">
        <canvas id="flower">
            <div class="tooltip">
                <span id ="tooltiptext" class="tooltiptextstyle">blah</span>
            </div>
        </canvas>
    </div>
</body>
</html>

Ответы [ 3 ]

3 голосов
/ 24 октября 2019

Было две проблемы:

  1. То, как вы применяли стили к своему холсту, приводило к тому, что его отображение не соответствовало его внутреннему отслеживанию положения содержащихся в нем элементов, поэтому *Условие 1004 * не обязательно возвращало значение true, когда курсор находился над тем местом, где кружок появлялся .
  2. Холст не может отображать и отображать содержимое .

Таким образом, приведенный ниже фрагмент показывает версию, которая работает. Вам нужно выяснить, как правильно расположить вещи, но это решает ближайшую проблему.

const canvas = document.getElementById('flower');
const ctx = canvas.getContext('2d');

const circle2 = new Path2D();
circle2.arc(100, 100, 25, 0, 2 * Math.PI);
ctx.fillStyle = "red";
ctx.fill(circle2);
                        
canvas.addEventListener("mousemove", function(event2) {
  if (ctx.isPointInPath(circle2, event2.clientX, event2.clientY)) {
    showtext();
  }
}); 
                        
function showtext(){
    document.getElementById("tooltiptext").style.visibility = 'visible';
}
html, body, div {
  width:  100%;
  height: 100%;
  margin: 0;
}
.tooltip {
    position: relative;
    display: inline-block;
    border-bottom: 1px dotted black; 
}
.tooltip .tooltiptextstyle {
    visibility: hidden; 
    display: block;
    width: 120px;
    background-color: black;
    color: #fff;
    text-align: center;
    padding: 5px 0;
    border-radius: 6px;
    position: absolute;
    z-index: 1;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link type="text/css" href="style.css"/>
    <script type="text/typescript" src="main.ts"></script>
</head>
<body>
    <div id="design" class="design">
        <canvas id="flower">
        </canvas>
        <div class="tooltip">
          <span id ="tooltiptext" class="tooltiptextstyle">
            blah
          </span>
      </div>
    </div>
</body>
</html>
3 голосов
/ 24 октября 2019

Проблема была в том, что вы установили ширину и высоту холста как 100% родительского элемента в CSS. Вместо этого вам нужно установить атрибут ширины и высоты холста.

html, body, div, canvas {
        width:  100%;
        height: 100%;
        margin: 0;
}
html, body, div {
        width:  100%;
        height: 100%;
        margin: 0;
}
<canvas id="canvas" width="200" height="200">

3 голосов
/ 24 октября 2019

вам нужно переместить элемент .tooltip из элемента canvas, иначе он не будет отображаться.

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// Create circle
const circle = new Path2D();
circle.arc(150, 75, 50, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill(circle);

// Listen for mouse moves
canvas.addEventListener('mousemove', function(event) {
  // Check whether point is inside circle
  if (ctx.isPointInPath(circle, event.clientX, event.clientY)) {
    showtext();
  } else {
    hidetext();
  }
});

function showtext() {
  document.getElementById("tooltiptext").style.visibility = 'visible';
}

function hidetext() {
  document.getElementById("tooltiptext").style.visibility = 'hidden';
}
.tooltip {
  visibility: hidden;
  position: absolute;
  top: 20px; left: 20px;
}

body {
  margin: 0;
}
<canvas id="canvas"></canvas>

<div class="tooltip">
  <span id="tooltiptext" class="tooltiptextstyle">blah</span>
</div>
...