网页技术交流
 
发新帖
楼主: 零五零八
查看: 636|回复: 0

[使用教程] canvas 绘图时位置偏离的问题解决

[复制链接]
零五零八 发表于 2020-11-23 19:00:09 | 显示全部楼层
使用 canvas 绘图时,指定的 div 大小一定不要超过该 div 所能获得的最大范围,否则绘制的点会跟实际位置发生偏离。
例如
  1. <html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  4. <title>Untitled 1</title>
  5. <style type="text/css">
  6. .style1 {
  7.   font-size: x-small;
  8. }
  9. </style>

  10. </head>
  11.   
  12. <body >
  13.     <div style="margin:2%">
  14.             <div id="test" style="width:800px;height:800px;background-color:#cbdad0d9">
  15.                     <canvas id="container" onmousemove="mousemove(event)" onmousedown="mousedown()" onmouseup="mouseup()"></canvas>
  16.             </div>
  17.     </div>
  18.      
  19.     <script type="text/javascript">
  20.         var paint = false;
  21.         var start = false;
  22.         var canvas = document.getElementById("container");
  23.         canvas.width = 800;
  24.         canvas.height = 800;
  25.         var offsetY = canvas.offsetTop;
  26.         var offsetX = canvas.offsetLeft;
  27.         var y;
  28.         var x;
  29.         var context = canvas.getContext("2d");
  30.      
  31.         function mousemove(e) {
  32.             if (paint == true){
  33.                 if (start == false){
  34.                     context.moveTo(0, 0);
  35.                     start = true;
  36.                 } else {
  37.                     context.moveTo(x, y);
  38.                 }

  39.                 x = e.pageX - offsetX;
  40.                 y = e.pageY - offsetY;
  41.                 context.lineTo(x, y);
  42.                 context.stroke();
  43.             }
  44.         }
  45.      
  46.         function mousedown(event) {
  47.             paint = true;
  48.             console.log("down")
  49.         }
  50.      
  51.         function mouseup(event) {
  52.             paint = false;
  53.             console.log("up")
  54.         }
  55.      
  56.     </script>
  57. </body>
  58. </html>
复制代码

上例中可以正确的绘制线图。
如果更改为:


  1. <div style="margin:20%">
  2.         <div id="test" style="width:800px;height:800px;background-color:#cbdad0d9">
  3.                 <canvas id="container" onmousemove="mousemove(event)" onmousedown="mousedown()" onmouseup="mouseup()"></canvas>
  4.         </div>
  5. </div>
复制代码

由于 canvas 所需 width 800px 无法满足,因此绘制线图时,与实际鼠标位置发生偏离




快速回复 返回顶部 返回列表