简体   繁体   English

跟进 Bizarre canvas position 通过设置初始值锁定

[英]Follow up to Bizarre canvas position locked by setting initial value

I posted a question about bizarre thing trying to change style.top of canvas.我发布了一个关于试图改变 canvas 的 style.top 的奇怪事情的问题。

People kindly advised tidy-up of code, but this still leaves me one unanswered question:人们好心地建议整理代码,但这仍然给我留下了一个悬而未决的问题:

its still the case that if I initialise the top or left positions of the canvas, it cant be moved.情况仍然如此,如果我初始化 canvas 的顶部或左侧位置,它就无法移动。 But it can if I never give it an initial value!但如果我从不给它一个初始值,它就可以!

In this example: you click on a canvas and should be able to move it- if style.top is given an initial value, it will stop canvas ever moving vertically similarly style.left value will stop it ever moving horizontally在这个例子中:你点击一个 canvas 并且应该能够移动它 - 如果 style.top 被赋予一个初始值,它将停止 canvas 垂直移动类似的 style.left 值将停止它水平移动

eg In the code below // comment out the top initial value, hence it will move vertically, but why??例如在下面的代码中//注释掉顶部的初始值,因此它会垂直移动,但为什么呢?

<!DOCTYPE html>
<html>
 <body>
  <script>
  var n=0, canv, ct
  var body = document.getElementsByTagName("body")[0];
  var i,offx=0,offy=0, n=0
  canv = document.createElement('canvas');
  canv.id = "C";
  canv.style.width = "100px";
  canv.style.height = "100px";
 //canv.style.top =  "50px"; commenting out line will let it move
  canv.style.left = "50px";
  canv.style.zIndex = 0;
  canv.style.position = "absolute";
  canv.style.border = "2px solid";
     
  body.appendChild(canv);
  ct = canv.getContext("2d");
    
  canv.addEventListener('mousedown', function (e) {
      if (this.style.border == "2px solid"){
          this.style.border = "5px solid"
          offy=e.y-this.style.top
          offx=e.x-this.style.left
       }
       else{this.style.border = "2px solid"}
    });
    
    canv.addEventListener('mousemove', function (e) {
       if (this.style.border != "2px solid"){
         this.style.top=e.y-offy+"px"
         this.style.left=e.x-offx+"px"
       }
    });
    
  </script>
 </body>
</html>

This is happening because this.style.top is a string, ending in px, so you can't subtract it like that:发生这种情况是因为 this.style.top 是一个字符串,以 px 结尾,所以你不能这样减去它:

offy=e.y-this.style.top

I made a few changes so that it is not trying to subtract strings in this fiddle.我做了一些更改,这样它就不会试图减去这个小提琴中的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM