canvas 绘图时位置偏离的问题解决
2020-09-20 04:09
627 查看
使用 canvas 绘图时,指定的 div 大小一定不要超过该 div 所能获得的最大范围,否则绘制的点会跟实际位置发生偏离。
例如
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled 1</title> <style type="text/css"> .style1 { font-size: x-small; } </style> </head> <body > <div style="margin:2%"> <div id="test" style="width:800px;height:800px;background-color:#cbdad0d9"> <canvas id="container" onmousemove="mousemove(event)" onmousedown="mousedown()" onmouseup="mouseup()"></canvas> </div> </div> <script type="text/javascript"> var paint = false; var start = false; var canvas = document.getElementById("container"); canvas.width = 800; canvas.height = 800; var offsetY = canvas.offsetTop; var offsetX = canvas.offsetLeft; var y; var x; var context = canvas.getContext("2d"); function mousemove(e) { if (paint == true){ if (start == false){ context.moveTo(0, 0); start = true; } else { context.moveTo(x, y); } x = e.pageX - offsetX; y = e.pageY - offsetY; context.lineTo(x, y); context.stroke(); } } function mousedown(event) { paint = true; console.log("down") } function mouseup(event) { paint = false; console.log("up") } </script> </body> </html>
上例中可以正确的绘制线图。
如果更改为:
<div style="margin:20%"> <div id="test" style="width:800px;height:800px;background-color:#cbdad0d9"> <canvas id="container" onmousemove="mousemove(event)" onmousedown="mousedown()" onmouseup="mouseup()"></canvas> </div> </div>
由于 canvas 所需 width 800px 无法满足,因此绘制线图时,与实际鼠标位置发生偏离。
到此这篇关于canvas 绘图时位置偏离的问题解决的文章就介绍到这了,更多相关canvas 绘图位置偏离内容请搜索脚本之家以前的文章或继续浏览下面的相关文章,希望大家以后多多支持脚本之家!
相关文章推荐
- cocos2dx js 关于canvas绘图模糊问题及解决办法
- canvas 使绘制的图片在div 居中显示 ,解决绘图模糊问题
- cocos2dx js 关于canvas绘图模糊问题及解决办法
- canvas 绘图出现模糊问题的解决方法
- cocos2dx js 关于canvas绘图模糊问题及解决办法
- VC 绘图闪屏问题解决
- 纯CSS+DIV轻松解决对象在任何位置上水平对齐的问题
- 解决NGUI的Poplist位置偏移问题
- 章鱼哥出品—VB.NET DataGridView绑定数据源 "与货币管理器的位置关联的行不能设置为不可见" 问题的解决
- 解决 html2canvas 白边问题,html2canvas 生成图片并下载,踩坑 html2canvas
- 解决绘图中闪烁的问题(C#)
- html2canvas跨域问题的简单解决方法
- android中画文字的换行 办法(对于遇到canvas.drawText(String s )无法实现换行问题的解决)
- 解决刷新界面滚动条位置还原的问题
- 关于沉浸式状态栏位置顶上去一部分的问题解决
- 困惑已久的记住浏览位置问题得到了解决
- iOS11 导航栏按钮位置问题的解决
- Tips3:Info.plist与Prefix.pch修改文件位置遇到的问题及解决方法
- C# 通过GDI+双缓冲解决绘图闪烁的问题
- vue实现pdf导出解决生成canvas模糊等问题(推荐)