获取鼠标点击位置 [英] Get mouse click position

查看:64
本文介绍了获取鼠标点击位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此色轮,并且我想在其上添加黑色封面色轮,通过这种方式,当使用色轮下方的滑块更改hsv的值(v)时,色轮将变暗.

I am using this color wheel, and I want to add a black cover overlay to the color wheel, this way when the hsv's value changes (the v) using the slider under the color wheel, the color wheel will become darker.

我在 canvas 中添加了一个包装器 div ,并在 wrapper 中添加了另一个div( overlay ),并将背景颜色设为黑色.然后,将 wrapper 的位置设置为 relative ,对于 overlay ,将位置设置为 absolute

I added a wrapper div to the canvas, and added another div (overlay) in the wrapper, and make the background color to black. I then set the position of the wrapper to relative, and for the overlay, I set the position to absolute.

(我将 wrapper 设置为 relative ,以便将 overlay (具有 absolute )包含在 wrapper .)

(I set wrapper to relative so that overlay (with is absolute) will be contained in the wrapper.)

由于 wrapper 设置为 relative ,因此色轮选择不正确.选择器无法完全跟随鼠标.

Because wrapper is set to relative, the color wheels selection isn't accurate. The picker doesn't follow the mouse exactly.

我认为可以通过编辑以下代码来解决该问题:(在 redraw()函数中,第69行.)

I think the problem can be solved with editing the following code: (In the redraw() function, on line 69.)

currentX = e.pageX - c.offsetLeft - radiusPlusOffset || currentX;
currentY = e.pageY - c.offsetTop - radiusPlusOffset  || currentY;

但是我不知道到底该更改什么.即使 wrapper 设置为 relative ,如何获取选择器指针来跟随鼠标?

But I don't know exactly what to change. How can I get the pickers pointer to follow the mouse even when wrapper is set to relative?

JSFiddle

(function() {

  // Declare constants and variables to help with minification
  // Some of these are inlined (with comments to the side with the actual equation)
  var doc = document;
  doc.c = doc.createElement;
  b.a = b.appendChild;

  var width = c.width = c.height = 400,
    label = b.a(doc.c("p")),
    input = b.a(doc.c("input")),
    imageData = a.createImageData(width, width),
    pixels = imageData.data,
    oneHundred = input.value = input.max = 100,
    circleOffset = 10,
    diameter = 380, //width-circleOffset*2,
    radius = 190, //diameter / 2,
    radiusPlusOffset = 200, //radius + circleOffset
    radiusSquared = radius * radius,
    two55 = 255,
    currentY = oneHundred,
    currentX = -currentY,
    wheelPixel = 16040; // circleOffset*4*width+circleOffset*4;

  // Math helpers
  var math = Math,
    PI = math.PI,
    PI2 = PI * 2,
    sqrt = math.sqrt,
    atan2 = math.atan2;

  // Setup DOM properties
  b.style.textAlign = "center";
  label.style.font = "2em courier";
  input.type = "range";

  // Load color wheel data into memory.
  for (y = input.min = 0; y < width; y++) {
    for (x = 0; x < width; x++) {
      var rx = x - radius,
        ry = y - radius,
        d = rx * rx + ry * ry,
        rgb = hsvToRgb(
          (atan2(ry, rx) + PI) / PI2, // Hue
          sqrt(d) / radius, // Saturation
          1 // Value
        );

      // Print current color, but hide if outside the area of the circle
      pixels[wheelPixel++] = rgb[0];
      pixels[wheelPixel++] = rgb[1];
      pixels[wheelPixel++] = rgb[2];
      pixels[wheelPixel++] = d > radiusSquared ? 0 : two55;
    }
  }

  // Bind Event Handlers
  input.onchange = redraw;
  c.onmousedown = doc.onmouseup = function(e) {
    // Unbind mousemove if this is a mouseup event, or bind mousemove if this a mousedown event
    doc.onmousemove = /p/.test(e.type) ? 0 : (redraw(e), redraw);
  }

  // Handle manual calls + mousemove event handler + input change event handler all in one place.
  function redraw(e) {

    // Only process an actual change if it is triggered by the mousemove or mousedown event.
    // Otherwise e.pageX will be undefined, which will cause the result to be NaN, so it will fallback to the current value
    currentX = e.pageX - c.offsetLeft - radiusPlusOffset || currentX;
    currentY = e.pageY - c.offsetTop - radiusPlusOffset || currentY;

    // Scope these locally so the compiler will minify the names.  Will manually remove the 'var' keyword in the minified version.
    var theta = atan2(currentY, currentX),
      d = currentX * currentX + currentY * currentY;

    // If the x/y is not in the circle, find angle between center and mouse point:
    //   Draw a line at that angle from center with the distance of radius
    //   Use that point on the circumference as the draggable location
    if (d > radiusSquared) {
      currentX = radius * math.cos(theta);
      currentY = radius * math.sin(theta);
      theta = atan2(currentY, currentX);
      d = currentX * currentX + currentY * currentY;
    }

    label.textContent = b.style.background = hsvToRgb(
      (theta + PI) / PI2, // Current hue (how many degrees along the circle)
      sqrt(d) / radius, // Current saturation (how close to the middle)
      input.value / oneHundred // Current value (input type="range" slider value)
    )[3];

    // Reset to color wheel and draw a spot on the current location. 
    a.putImageData(imageData, 0, 0);

    // Heart:
    a.font = "1em arial";
    a.fillText("♥", currentX + radiusPlusOffset - 4, currentY + radiusPlusOffset + 4);

  }

  // Created a shorter version of the HSV to RGB conversion function in TinyColor
  // https://github.com/bgrins/TinyColor/blob/master/tinycolor.js
  function hsvToRgb(h, s, v) {
    h *= 6;
    var i = ~~h,
      f = h - i,
      p = v * (1 - s),
      q = v * (1 - f * s),
      t = v * (1 - (1 - f) * s),
      mod = i % 6,
      r = [v, q, p, p, t, v][mod] * two55,
      g = [t, v, v, q, p, p][mod] * two55,
      b = [p, p, t, v, v, q][mod] * two55;

    return [r, g, b, "rgb(" + ~~r + "," + ~~g + "," + ~~b + ")"];
  }

  // Kick everything off
  redraw(0);

  /*
  // Just an idea I had to kick everything off with some changing colors…
  // Probably no way to squeeze this into 1k, but it could probably be a lot smaller than this:
  currentX = currentY = 1;
  var interval = setInterval(function() {
      currentX--;
      currentY*=1.05;
      redraw(0)
  }, 7);
    
  setTimeout(function() {
      clearInterval(interval)
  }, 700)
  */

})();

#wrapper {
  width: 400px;
  height: 400px;
  position: relative;
}
#blackBackground {
  background-color: black;
  width: 100%;
  height: 100%;
  position: absolute;
  border-radius: 50%;
  opacity: .5;
  pointer-events: none;
}

<div>
  Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis,
  sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus
  elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum.
  Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit
  vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh.
  Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,
</div>

<div id="wrapper">
  <div id="blackBackground"></div>
  <canvas id="c"></canvas>
</div>

<script>
  var b = document.body;
  var c = document.getElementsByTagName('canvas')[0];
  var a = c.getContext('2d');
  document.body.clientWidth; // fix bug in webkit: http://qfox.nl/weblog/218
</script>

推荐答案

将其添加到最后一个脚本标记中(紧随 var c = ... 之后):

Add this to the last script tag (just after var c = ...):

var w = document.getElementById('wrapper');

然后您可以获取并减去包装器偏移量属性:

then You can get and substract the wrapper offset properties:

currentX = e.pageX - w.offsetLeft - c.offsetLeft - radiusPlusOffset || currentX;
currentY = e.pageY - w.offsetTop - c.offsetTop - radiusPlusOffset || currentY;

这篇关于获取鼠标点击位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆