如何将浏览器中的坐标转换为 canvas 中的坐标

news/2024/7/19 14:36:45 标签: js, html5, canvas
function convertToCanvas(canvas, x, y} {
	const canvasElement  = canvas.getBoundingClientRect() ;
	return { x: (x- canvasElement.left)*(canvas.width  / canvasElement.width),
			y: (y - canvasElement.top)*(canvas.height / canvasElement.height)
	}
}

转换的逻辑是先使用鼠标事件中相对于浏览器文档的坐标减去 canvas 左上角的坐标,然后进行相应的缩放,之所以要进行缩放,是因为 canvas 在页面中显示的大小和实际的大小不一定是 1:1 的关系, 这是因为 canvas 实际的大小是通过 canvas 标签的 width 、 height 属性指定的,而显示的大小可以通过 css 来指定,这是两套互相独立的值,从而导致显示的大小和实际的大小不 定是 1:1 的关系 例如, canvas 本身的宽和高分别是 300 、150 ,而 css中设置为 600 、 600 ,那么 canvas 轴方向的 个像素显示到页面中的就是 2个像素,而canvas中y 轴方向的 1个像素显示到页面中是4个像素,因此需要进行缩放。


http://www.niftyadmin.cn/n/1367765.html

相关文章

js浏览器版本判断

// 判断是否为IE浏览器 function isIE () {const bw window.navigator.userAgent// ie版本 10 及以下const compare (s) > bw.indexOf(s) > 0// ie 11const ie11 (() > ActiveXObject in window)()return compare(MSIE) || ie11 } isChrome() {const e navigator.…

vue动态路由刷新后无限循环、页面空白

使用的是PanJiaChen大佬的vue-admin-template模板 下载大佬的权限管理模板运行正常,自己用来改造刷新就无限循环or页面空白,下面是改造成功的permission.js相关代码 // !!!自己项目不需要token const hasGetUserInfo…

vue倒计时60秒

// _cutime 60resetTime(){let timerconst countDown ()>{this.time--;if(this.time < 0){clearInterval(timer);this.time _cutimethis.$forceUpdate()return}timersetTimeout(countDown,1000);}countDown()},

IE下载文件流,文件后缀名丢失

谷歌内核正常,IE下载无后缀名&#xff0c;打不开 本次项目需要下载的文件就两种格式xlsx和zip所以走ie时手动添加后缀名就可以搞定了 export const download async({ url, params, method post, type xlsx }) > {const isget method.toLowerCase() get;const obj is…

vue Element-ui el-table合计行样式自定义、不换行显示

本项目由于合计汇总数字太多太长&#xff0c;又不能改变原width的情况下&#xff0c;就自定义样式超出点点点了&#xff0c;又要鼠标悬浮看全。js&#xff08;设置‘title’&#xff09; 配合 css&#xff08;不换行&#xff09; watch: {//loading 为v-loadingloading(bool) {…

vue Element-ui el-table刷新列表后自动滚动到高亮行

const Tbody this.$refs.multipleTable.$el.querySelector(.el-table__body-wrapper> table > tbody) setTimeout(() > {Tbody.querySelector(.el-table__row.current-row)?.scrollIntoView({ behavior: instant, block: center, inline: nearest }) }, 300)

前端自定义导出Excel

import FileSaver from file-saver; import XLSX from xlsx;function exportExcel(_dataSource) {var wopts {bookType: xlsx,bookSST: true,type: binary};var workBook {SheetNames: [Sheet1],Sheets: {},Props: {}};let dataSource [{ 暂无数据: 暂无数据 }];const tabel…

input 标签 accept 属性兼容问题

// 使用application/vnd.ms-powerpoint 类型时&#xff0c;一些浏览器打开是ppa,一些打开没有ppt 或 pptx// 使用以下方式完美解决 <input accept".xls,.xlsx,.doc,.docx,.ppt,.pptx" />其他类型