• <tfoot id='E4k6w'></tfoot>

        <small id='E4k6w'></small><noframes id='E4k6w'>

          <bdo id='E4k6w'></bdo><ul id='E4k6w'></ul>

        <legend id='E4k6w'><style id='E4k6w'><dir id='E4k6w'><q id='E4k6w'></q></dir></style></legend>
        <i id='E4k6w'><tr id='E4k6w'><dt id='E4k6w'><q id='E4k6w'><span id='E4k6w'><b id='E4k6w'><form id='E4k6w'><ins id='E4k6w'></ins><ul id='E4k6w'></ul><sub id='E4k6w'></sub></form><legend id='E4k6w'></legend><bdo id='E4k6w'><pre id='E4k6w'><center id='E4k6w'></center></pre></bdo></b><th id='E4k6w'></th></span></q></dt></tr></i><div id='E4k6w'><tfoot id='E4k6w'></tfoot><dl id='E4k6w'><fieldset id='E4k6w'></fieldset></dl></div>

      1. 缩放和平移画布后鼠标坐标不匹配

        Mouse coordinates don#39;t match after Scaling and Panning canvas(缩放和平移画布后鼠标坐标不匹配)

            <i id='ykOss'><tr id='ykOss'><dt id='ykOss'><q id='ykOss'><span id='ykOss'><b id='ykOss'><form id='ykOss'><ins id='ykOss'></ins><ul id='ykOss'></ul><sub id='ykOss'></sub></form><legend id='ykOss'></legend><bdo id='ykOss'><pre id='ykOss'><center id='ykOss'></center></pre></bdo></b><th id='ykOss'></th></span></q></dt></tr></i><div id='ykOss'><tfoot id='ykOss'></tfoot><dl id='ykOss'><fieldset id='ykOss'></fieldset></dl></div>
            1. <legend id='ykOss'><style id='ykOss'><dir id='ykOss'><q id='ykOss'></q></dir></style></legend>

              <tfoot id='ykOss'></tfoot>
                  <bdo id='ykOss'></bdo><ul id='ykOss'></ul>
                    <tbody id='ykOss'></tbody>
                • <small id='ykOss'></small><noframes id='ykOss'>

                  本文介绍了缩放和平移画布后鼠标坐标不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                  问题描述

                  我对 javascript 和 canvas 非常陌生,我有一个程序可以检测椭圆路径上的动画元素.它稍后会形成一棵树.但这是我链接到 jsfiddle 的基本结构.它可以在没有缩放或平移的情况下正常工作,但是一旦我尝试缩放或平移,鼠标坐标就会变得混乱.我尝试遵循 HTML5 画布在缩放和翻译后获取坐标但我肯定做错了什么,我显然不明白画布和转换矩阵发生了什么.我花了大约 3 天的时间试图改变我能想到的所有组合,但我似乎无法弄清楚:s

                  I'm very new to javascript and canvas and I have a program that's supposed to detect elements animated on an elliptical path. It later on goes to form a tree.. But this is the basic structure that I've linked onto jsfiddle. It works fine without scaling or panning but as soon as I try to scale or Pan, the mouse coordinates go haywire. I tried following markE's advice from HTML5 canvas get coordinates after zoom and translate But i'm definitely doing something wrong and I've clearly not understood whats happening with the canvas and the transformation matrix. I've spent about 3 days trying to change all the combinations I can think of but I can't seem to figure it out :s

                  已解决:这是我的代码,其中包含缩放和鼠标平移以及用于动画和检测椭圆上的元素:http://jsfiddle.net/metalloyd/A8hgz/

                  SOLVED: Here's my code with zooming and mouse panning and for animating and detecting elements on an ellipse: http://jsfiddle.net/metalloyd/A8hgz/

                              theCanvas = document.getElementById("canvasOne");
                              context = theCanvas.getContext("2d");
                              var status = document.getElementById('status');
                              var $canvas = $("#canvasOne");
                              var canvasOffset = $canvas.offset();
                              var offsetX = canvasOffset.left;
                              var offsetY = canvasOffset.top;
                              var scrollX = $canvas.scrollLeft();
                              var scrollY = $canvas.scrollTop();
                              var cw = theCanvas.width;
                              var ch = theCanvas.height;
                              var scaleFactor = 1.00;
                              var panX = 0;
                              var panY = 0;
                  
                              var mainX = 250;
                              // setting the middle point position X value
                              var mainY = 100;
                              // setting the middle point position Y value
                              var mainR = 125;
                              // main ellipse radius R
                              var no = 5;
                              // number of nodes to display
                              var div_angle = 360 / no;
                  
                              var circle = {
                                  centerX: mainX,
                                  centerY: mainY + 100,
                                  radius: mainR,
                                  angle: .9
                              };
                  
                              var ball = {
                                  x: 0,
                                  y: 0,
                                  speed: .1
                              };
                              var a = 1.8;
                              //Ellipse width
                              var b = .5;
                              //Ellipse height
                  
                             //Scale and Pan variables
                              var translatePos = {
                                  x: 1,
                                  y: 1
                              };
                              var startDragOffset = {};
                              var mouseDown = false;
                  
                              var elements = [{}];
                  
                              // Animate
                              var animateInterval = setInterval(drawScreen, 1);
                  
                              //Animation
                              function drawScreen() {
                                  context.clearRect(0, 0, cw, ch);
                                  // Background box
                                  context.beginPath();
                                  context.fillStyle = '#EEEEEE';
                                  context.fillRect(0, 0, theCanvas.width, theCanvas.height);
                                  context.strokeRect(1, 1, theCanvas.width - 2, theCanvas.height - 2);
                                  context.closePath();
                  
                                  context.save();
                                  context.translate(panX, panY);
                                  context.scale(scaleFactor, scaleFactor);
                  
                                  ball.speed = ball.speed + 0.001;
                  
                                  for (var i = 1; i <= no; i++) {
                                      // male
                                      new_angle = div_angle * i;
                                      //Starting positions for ball 1 at different points on the ellipse
                                      circle.angle = (new_angle * (0.0174532925)) + ball.speed;
                                      //elliptical x position and y position for animation for the first ball
                                      //xx and yy records the first balls coordinates
                                      xx = ball.x = circle.centerX - (a * Math.cos(circle.angle)) * (circle.radius);
                                      yy = ball.y = circle.centerY + (b * Math.sin(circle.angle)) * (circle.radius);
                                      //Draw the first ball with position x and y
                                      context.fillStyle = "#000000";
                                      context.beginPath();
                                      context.arc(ball.x, ball.y, 10, 0, Math.PI * 2, true);
                                      context.fill();
                                      context.closePath();
                  
                                      //alert("male Positions "+"X:  "+ball.x+ " Y: "+ball.y);
                  
                                      // female
                                      new_angle = div_angle * i + 4;
                                      //Starting positions for ball 2 at different points on the ellipse
                                      circle.angle = (new_angle * (0.0174532925)) + ball.speed;
                                      //elliptical x position and y position for animation for the second ball
                                      //ball.x and ball.y record the second balls positions
                                      ball.x = circle.centerX - (a * Math.cos(circle.angle)) * (circle.radius);
                                      ball.y = circle.centerY + (b * Math.sin(circle.angle)) * (circle.radius);
                                      context.fillStyle = "#000000";
                                      context.beginPath();
                                      context.arc(ball.x, ball.y, 10, 0, Math.PI * 2, true);
                                      context.fill();
                                      context.closePath();
                  
                                      //alert("female Positions "+"X:  "+ball.x+ " Y: "+ball.y);
                  
                                      //Record the ball positions in elements array for locating positions with mouse coordinates.
                                      elements[i] = {
                                          id: i,
                                          femaleX: ball.x,
                                          femaleY: ball.y,
                                          maleX: xx,
                                          maleY: yy,
                                          w: 10 //radius of the ball to draw while locating the positions
                                      };
                                      //Text Numbering
                                      context.beginPath();
                                      context.fillStyle = "blue";
                                      context.font = "bold 16px Arial";
                                      context.fillText(elements[i].id, ball.x - 20, ball.y + 20);
                                      context.closePath();
                                      // line drawing--Connecting lines to the balls from the center.
                                      context.moveTo(mainX, mainY);
                                      context.lineTo((ball.x + xx) / 2, (ball.y + yy) / 2);
                                      //Draw line till the middle point between ball1 and ball2
                                      context.stroke();
                                      context.fill();
                                      context.closePath();
                                  }
                                  // center point
                                  context.fillStyle = "#000000";
                                  context.beginPath();
                                  context.arc(mainX, mainY, 15, 0, Math.PI * 2, true);
                                  context.fill();
                                  context.closePath();
                  
                                  context.restore();
                              }
                  
                              // Event Listeners
                              // Mouse move event to alert the position of the ball on screen
                  
                  
                              document.getElementById("plus").addEventListener("click", function () {
                                  scaleFactor *= 1.1;
                                  drawScreen();
                              }, false);
                  
                              document.getElementById("minus").addEventListener("click", function () {
                                  scaleFactor /= 1.1;
                                  drawScreen();
                              }, false);
                  
                              // Event listeners to handle screen panning
                              context.canvas.addEventListener("mousedown", function (evt) {
                                  mouseDown = true;
                                  startDragOffset.x = evt.clientX - translatePos.x;
                                  startDragOffset.y = evt.clientY - translatePos.y;
                              });
                  
                              context.canvas.addEventListener("mouseup", function (evt) {
                                  mouseDown = false;
                              });
                  
                              context.canvas.addEventListener("mouseover", function (evt) {
                                  mouseDown = false;
                              });
                  
                              context.canvas.addEventListener("mouseout", function (evt) {
                                  mouseDown = false;
                              });
                  
                              context.canvas.addEventListener("mousemove", function (evt) {
                                  if (mouseDown) {
                                      translatePos.x = evt.clientX - startDragOffset.x;
                                      translatePos.y = evt.clientY - startDragOffset.y;
                  
                                      panX = translatePos.x;
                                      panY = translatePos.y;
                  
                                      drawScreen();
                                  }
                  
                                  evt.preventDefault();
                                  evt.stopPropagation();
                  
                                  var mouseX = parseInt(evt.clientX - offsetX);
                                  var mouseY = parseInt(evt.clientY - offsetY);
                  
                                  var mouseXT = parseInt((mouseX - panX) / scaleFactor);
                                  var mouseYT = parseInt((mouseY - panY) / scaleFactor);
                  
                                  status.innerHTML = mouseXT + " | " + mouseYT;
                  
                                  for (var i = 1; i < elements.length; i++) {
                                      var b = elements[i];
                                      context.closePath();
                                      context.beginPath();
                                      context.arc(b.femaleX, b.femaleY, 10, 0, Math.PI * 2);
                                      context.arc(b.maleX, b.maleY, 10, 0, Math.PI * 2);
                  
                                      if (context.isPointInPath(mouseXT, mouseYT)) {
                                          theCanvas.style.cursor = 'pointer';
                                          alert(b.id + " female.x: " + b.femaleX + " female.y: " + b.femaleY + " ball.x: " + ball.x + " ball.y: " + ball.y);
                                          return;
                                      } else theCanvas.style.cursor = 'default';
                                      context.closePath();
                                  }
                  
                              });`
                  

                  推荐答案

                  在这些情况下使用变换矩阵很有用,甚至是必要的:

                  Using the transformation matrix is useful or even necessary in these circumstances:

                  • 如果您正在深度嵌套转换.
                  • 如果您使用不同的变换更改不同的图纸.
                  • 如果您需要临时变换坐标.
                  • 如果您正在进行涉及倾斜的转换.
                  • 如果您正在进行涉及旋转的变换.

                  但是对于平移和缩放整个画布的更简单的情况,有一个更简单的方法.

                  But for the simpler case of panning and scaling the entire canvas there is a simpler method.

                  首先,设置变量来保存当前的缩放和平移量:

                  var scaleFactor=1.00;
                  var panX=0;
                  var panY=0;
                  

                  然后使用这些 pan &缩放变量以完成所有绘图.

                  • 清除画布.
                  • 保存未转换的画布状态.
                  • 使用 panX 变量进行翻译.
                  • 使用 scaleFactor 变量进行缩放.
                  • 绘制所有元素,就好像它们在未转换的空间中一样.
                  • 将上下文恢复到未转换的状态.
                  • clear the canvas.
                  • save the untransformed canvas state.
                  • do translations with the panX variable.
                  • do scaling with the scaleFactor variable.
                  • draw all your elements as if they were in untranformed space.
                  • restore the context to its untransformed state.

                  示例代码:

                  function drawTranslated(){
                  
                      ctx.clearRect(0,0,cw,ch);
                  
                      ctx.save();
                      ctx.translate(panX,panY);
                      ctx.scale(scaleFactor,scaleFactor);
                  
                      ctx.beginPath();
                      ctx.arc(circleX,circleY,15,0,Math.PI*2);
                      ctx.closePath();
                      ctx.fillStyle=randomColor();
                      ctx.fill();
                  
                      ctx.restore();
                  
                  }
                  

                  现在,关于鼠标坐标:

                  浏览器总是以未转换的坐标返回鼠标位置.您的绘画是在变形空间中完成的.如果您想知道鼠标在变换空间中的位置,可以将未变换的鼠标坐标转换为变换的坐标,如下所示:

                  The browser always returns the mouse position in untransformed coordinates. Your drawings have been done in transformed space. If you want to know where your mouse is in transformed space, you can convert untransformed mouse coordinates to transformed coordinates like this:

                  var mouseXTransformed = (mouseX-panX) / scaleFactor;
                  var mouseYTransformed = (mouseY-panY) / scaleFactor;
                  

                  这是示例代码和演示: http://jsfiddle.net/m1erickson/HwNp3/

                  <!doctype html>
                  <html>
                  <head>
                  <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
                  <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
                  <style>
                      body{ background-color: ivory; }
                      #canvas{border:1px solid red;}
                  </style>
                  <script>
                  $(function(){
                  
                      var canvas=document.getElementById("canvas");
                      var ctx=canvas.getContext("2d");
                      var $canvas=$("#canvas");
                      var canvasOffset=$canvas.offset();
                      var offsetX=canvasOffset.left;
                      var offsetY=canvasOffset.top;
                      var scrollX=$canvas.scrollLeft();
                      var scrollY=$canvas.scrollTop();
                      var cw=canvas.width;
                      var ch=canvas.height;
                  
                      var scaleFactor=1.00;
                      var panX=0;
                      var panY=0;
                  
                      var circleX=150;
                      var circleY=150;
                  
                      var $screen=$("#screen");
                      var $transformed=$("#transformed");
                      var $trx=$("#trx");
                  
                      drawTranslated();
                  
                      $("#canvas").mousemove(function(e){handleMouseMove(e);});
                      $("#scaledown").click(function(){ scaleFactor/=1.1; drawTranslated(); });
                      $("#scaleup").click(function(){ scaleFactor*=1.1; drawTranslated(); });
                      $("#panleft").click(function(){ panX-=10; drawTranslated(); });
                      $("#panright").click(function(){ panX+=10; drawTranslated(); });
                  
                  
                      function drawTranslated(){
                          ctx.clearRect(0,0,cw,ch);
                  
                          ctx.save();
                          ctx.translate(panX,panY);
                          ctx.scale(scaleFactor,scaleFactor);
                  
                          ctx.beginPath();
                          ctx.arc(circleX,circleY,15,0,Math.PI*2);
                          ctx.closePath();
                          ctx.fillStyle=randomColor();
                          ctx.fill();
                  
                          ctx.restore();
                  
                          $trx.text("Pan: "+panX+", Scale: "+scaleFactor);
                      }
                  
                      function handleMouseMove(e){
                          e.preventDefault();
                          e.stopPropagation();
                  
                          var mouseX=parseInt(e.clientX-offsetX);
                          var mouseY=parseInt(e.clientY-offsetY);
                  
                          var mouseXT=parseInt((mouseX-panX)/scaleFactor);
                          var mouseYT=parseInt((mouseY-panY)/scaleFactor);
                  
                          $screen.text("Screen Coordinates: "+mouseX+"/"+mouseY);
                  
                          $transformed.text("Transformed Coordinates: "+mouseXT+"/"+mouseYT);
                      }
                  
                      function randomColor(){ 
                          return('#'+Math.floor(Math.random()*16777215).toString(16));
                      }
                  
                  }); // end $(function(){});
                  </script>
                  </head>
                  <body>
                      <h3>Transformed coordinates are mouseXY in transformed space.<br>The circles center is always at translated [150,150]</h3>
                      <h4 id=screen>Screen Coordinates:</h4>
                      <h4 id=transformed>Transformed Coordinates:</h4>
                      <h4 id=trx>Pan & Scale</h4>
                      <button id=scaledown>Scale Down</button>
                      <button id=scaleup>Scale Up</button>
                      <button id=panleft>Pan Left</button>
                      <button id=panright>Pan Right</button><br>
                      <canvas id="canvas" width=350 height=400></canvas>
                  </body>
                  </html>
                  

                  这篇关于缩放和平移画布后鼠标坐标不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                  相关文档推荐

                  How does object-fit work with canvas element?(对象适合如何与画布元素一起使用?)
                  How to make rooftext effect and valley text effect in HTML5 (or Fabric.js)(如何在 HTML5(或 Fabric.js)中制作屋顶文字效果和山谷文字效果)
                  Draw border around nontransparent part of image on canvas(在画布上的图像不透明部分周围绘制边框)
                  dragging and resizing an image on html5 canvas(在 html5 画布上拖动图像并调整其大小)
                  What#39;s the difference between a boolean as primitive and a boolean as property of an object?(作为原始对象的布尔值和作为对象属性的布尔值有什么区别?)
                  I want to do animation of an object along a particular path(我想沿特定路径对对象进行动画处理)

                  <legend id='9Z2ea'><style id='9Z2ea'><dir id='9Z2ea'><q id='9Z2ea'></q></dir></style></legend>
                          <tbody id='9Z2ea'></tbody>

                        <small id='9Z2ea'></small><noframes id='9Z2ea'>

                          <tfoot id='9Z2ea'></tfoot>
                          <i id='9Z2ea'><tr id='9Z2ea'><dt id='9Z2ea'><q id='9Z2ea'><span id='9Z2ea'><b id='9Z2ea'><form id='9Z2ea'><ins id='9Z2ea'></ins><ul id='9Z2ea'></ul><sub id='9Z2ea'></sub></form><legend id='9Z2ea'></legend><bdo id='9Z2ea'><pre id='9Z2ea'><center id='9Z2ea'></center></pre></bdo></b><th id='9Z2ea'></th></span></q></dt></tr></i><div id='9Z2ea'><tfoot id='9Z2ea'></tfoot><dl id='9Z2ea'><fieldset id='9Z2ea'></fieldset></dl></div>

                            <bdo id='9Z2ea'></bdo><ul id='9Z2ea'></ul>