Note that there are some explanatory texts on larger screens.

plurals
  1. POHTML5 canvas lines are drawn with some offset
    text
    copied!<p>I am having some problems with drawing lines on a Canvas using Javascript. </p> <p>I have a page which contains a canvas and some small divs:</p> <pre><code>&lt;canvas id="myCanvas" width ="500" height="500"&gt;&lt;/canvas&gt; &lt;div id="1111" title ="test div1" style=" position:absolute; left: 10px; top: 30px; z-index:3; width:6px; height:6px; background-color:green"&gt; &lt;/div&gt; &lt;div id="2222" title ="test div2" style=" position:absolute; left: 90px; top: 30px; z-index:3; width:6px; height:6px; background-color:black;"&gt; &lt;/div&gt; &lt;div id="3333" title ="test div4" style=" position:absolute; left: 50px; top: 60px; z-index:3; width:6px; height:6px; background-color:blue; "&gt; &lt;/div&gt; &lt;div id="4444" title ="test div3" style=" position:absolute; left: 70px; top: 70px; z-index:3; width:6px; height:6px; background-color:yellow;"&gt; &lt;/div&gt; </code></pre> <p>and some Javascript code that draws lines from one div to another using jquery to get the divs position:</p> <pre><code>&lt;script&gt; var canv = document.getElementById("myCanvas"); var div1 = "1111"; var div2 = "2222"; var div3 = "3333"; var left_1= $("#"+div1).css("left") ; var top_1= $("#"+div1).css("top") ; left_1=parseFloat(left_1); top_1=parseFloat(top_1); var left_2= $("#"+div2).css("left") ; var top_2= $("#"+div2).css("top") ; left_2=parseFloat(left_2); top_2=parseFloat(top_2); var left_3= $("#"+ div3).css("left") ; var top_3= $("#"+ div3).css("top") ; left_3=parseFloat(left_3); top_3=parseFloat(top_3); var cxt=canv.getContext("2d"); cxt.lineWidth=5; cxt.strokeStyle="#FF0000"; cxt.moveTo(left_1,top_1); cxt.lineTo(left_2,top_2); cxt.lineTo(left_3,top_3); cxt.stroke(); </code></pre> <p></p> <p>The problem is that the lines drawn are some pixel far from where they are supposed to be. I know that the left and top attributes of the div represent the top-left corner of the div, so I don't understand why the lines are drawn closer to the low-right corner. The strangest thing is that this behaviour is persisten with the latest Firefox, Safari and Chrome for mac but does not verify using jsfiddle.net: </p> <p><a href="http://jsfiddle.net/KnmXb/" rel="nofollow">http://jsfiddle.net/KnmXb/</a> </p> <p>This is how the page is supposed to behave. I noticed that deselecting "Normalized CSS" in jsfiddle draws the lines in the very same manner safari, firefox and chrome are doing.</p> <p>Can anyone tell me if I'm doing something wrong?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload