javascript - 无法将坐标精确到 Canvas

标签 javascript html css

这是一个相机捕捉笔,我想做的就是根据 mouseX、mouseY 将源图像的精确坐标发送到 Canvas ,它有点像裁剪工具。 这是笔代码来源: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"
})

最佳答案

两件事:

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

在点击处理程序中:

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

例如:

var y = e.clientY - z + 100;

See the updated pen

关于javascript - 无法将坐标精确到 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54852632/

相关文章:

html - 如何将 CSS 样式添加到 HTML 中的聚焦 anchor

python - 以固定行和列标题的 html 形式查看 tsv 表

html - 下拉菜单和子菜单之间的差距

javascript - React native 0.62.0 - Android 上的文件上传网络请求错误

javascript - Angular base64 视频插值失败($sce)

html - 溢出隐藏设置在 IE 11、Firefox 中不起作用

html - 不透明度影响元素被另一个元素隐藏的方式

css - asp.net budle.config 不包括新的 css 文件

javascript - 根据分辨率将显示属性添加到折叠式 onload

javascript - 如何在查询时使用 Firebase Cloud Functions 中的 forEach?