【问题标题】:Can't accurate coords to canvas无法准确定位到画布
【发布时间】:2019-02-25 02:12:01
【问题描述】:

这是一个相机捕捉笔,我想要做的就是根据 mouseX、mouseY 将源图像坐标的确切发送到画布,它就像一个裁剪工具。 这里是笔码源:https://codepen.io/Mahmoud-Zakaria/pen/QKmZBO

<a href="#modal-wrap">
  <div class="camera-square"></div>
  <div class="camera-square"></div>
  <div class="camera-square"></div>
  <div class="camera-square"></div>
  <span class="camera-circle"></span>
</a>


<div class="camera" id="camera">
  <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/306097/rfAMYT.jpg" alt="">
</div>

<div class="modal-wrap" id="modal-wrap">
  <div class="modal-surround" id="modal-surround"></div>
  <div class="modal" id="modal">
    <canvas id="modal-target" class="modal-target"></canvas>
    <a href="#" class="modal-close" id="modal-close">&times;</a>
  </div>
</div>
window.location.href = '#'

var cameraCursor = document.querySelector('[href="#modal-wrap"]')
var cameraWrap = document.getElementById('camera')
var modalTarget = document.getElementById('modal-target');
const modalTargetContext = modalTarget.getContext('2d');
var img = document.getElementsByTagName('img')[0]
var sound = document.getElementsByTagName('audio')[0]
var modalClose = document.getElementById('modal-close')


window.addEventListener('mousemove', function(e) {
  cameraCursor.style.top = e.clientY - (cameraCursor.offsetHeight - (cameraCursor.offsetHeight / 2)) + 'px';
  cameraCursor.style.left = e.clientX - (cameraCursor.offsetWidth - (cameraCursor.offsetWidth / 2)) + 'px';
})


cameraCursor.addEventListener('click', function(e) {
  this.style.cursor = "default"
  this.style.opacity = "0"
  sound.play()
  var o = (cameraCursor.offsetWidth / 2)
  var z = (cameraCursor.offsetHeight / 2)
  var x = e.clientX - o;
  var y = e.clientY - z;
  modalTargetContext.drawImage(img, x, y, img.offsetWidth, img.offsetHeight, 0, 0, img.offsetWidth / 2, img.offsetHeight / 2);
})

modalClose.addEventListener('click', function(){
  cameraCursor.style.opacity = '1'
  cameraCursor.style.cursor = "none"
})

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    两件事:

    1. 模式中的canvas 没有设置特定的宽度和高度。这将其默认为 300x150,通过 css 应用任何宽度/高度只会缩放它。您应该在 html 中明确设置它,或者更好的是,通过getBoundingClientRect() 读取所需的宽度和高度,然后在绘制之前应用它。

    在点击处理程序内部:

    var bounds = modalTarget.getBoundingClientRect()
    modalTarget.width = bounds.width
    modalTarget.height = bounds.height
    modalTargetContext.drawImage(...)
    
    1. 您的图片具有 -100 像素的垂直 css 偏移量,这需要考虑到坐标中。

    例如:

    var y = e.clientY - z + 100;
    

    See the updated pen

    【讨论】:

      猜你喜欢
      • 2022-01-28
      • 2021-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多