欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

在Vue中实现点击图片获取像素坐标的操作

最编程 2024-08-07 20:21:23
...
<template> <div> <img ref="image" width="1500px" :src="imageUrl" @click="handleClick"> <div v-if="showCoords">X: {{ x }}, Y: {{ y }}</div> </div> </template> <script> export default { data() { return { imageUrl: 'https://dashanbook.oss-cn-shenzhen.aliyuncs.com/11.png', showCoords: false, x: 0, y: 0, naturalWidth: 0, naturalHeight: 0 }; }, mounted() { const image = this.$refs.image; image.addEventListener('load', () => { this.naturalWidth = image.naturalWidth; this.naturalHeight = image.naturalHeight; }); }, methods: { handleClick(event) { const image = this.$refs.image; const rect = image.getBoundingClientRect(); const x = (event.clientX - rect.left) * (this.naturalWidth / image.width); const y = (event.clientY - rect.top) * (this.naturalHeight / image.height); this.x = x; this.y = y; this.showCoords = true; }, }, }; </script>