Подчеркните координаты, когда они находятся в пределах 20px от центра - PullRequest
1 голос
/ 29 марта 2020

У меня есть div, действующий как холст, который показывает координаты, где находится мышь на этом холсте. Я пытаюсь добиться того, чтобы координаты были подчеркнуты, когда они находятся в пределах 20 пикселей от центра, но я не уверен, как к нему приблизиться, поскольку я новичок в VueJS.

HTML:

<div id="canvas" v-bind:class="canvasClasses"  @mousemove="getCoordinates">
    {{coordinates.x}},{{coordinates.y}}
</div>

JS:

var canvas = new Vue ({
    el: '#canvas',
    data: {
        canvasClasses: ["canvas", "font"],
        underlineClass: ["underlineFont"],
        coordinates: {
            x: 0,
            y: 0
        } 
    },
    methods: {
        getCoordinates(ml){
            this.coordinates.x = ml.offsetX;
            this.coordinates.y = ml.offsetY;
        }
    }
})

CSS:

.canvas{
    width: 500px;
    height: 500px;
    display: block;
    margin-left: auto;
    margin-right: auto;
    padding: 0;
    background-color: #74b9ff;
}

.font{
    font-family: monospace;
    font-size: 1.5rem;
    color: #FFFFFF;
}

.underlineFont{
    text-decoration: underline;
}

1 Ответ

0 голосов
/ 29 марта 2020

Создайте привязку класса для координат, которая возвращает значение underlineClass, если выполнены требования к радиусу:

<span :class="coordsClass">{{coordinates.x}},{{coordinates.y}}</span>

. Вычисленный проверяет, находятся ли текущие x и y в пределах границы радиуса и, если это так, возвращает имя класса (иначе имя класса не возвращается):

computed: {
  coordsClass() {
    const x = this.coordinates.x;
    const y = this.coordinates.y;
    const xO = this.origin.x;
    const yO = this.origin.y;
    if ( x >= xO - this.radius && x <= xO + this.radius
      && y >= yO - this.radius && y <= yO + this.radius ) {
      return this.underlineClass; 
    }
  }

Используйте radius и origin, объявленные в data:

data() {
  return {
    ... // Other data
    origin: {
      x: 0,
      y: 0
    },
    radius: 20 // Size of radius in pixels
  }
}

Рассчитайте origin, когда компонент смонтирован:

mounted() {
  this.origin.x = this.$el.clientWidth / 2;
  this.origin.y = this.$el.clientHeight / 2;
}

Вот демоверсия

...