2015-10-15 20 views
5

我想創建一個簡單的頁面,您可以點擊並在畫布上創建矩形。它將用戶的鼠標點擊作爲輸入,然後從點擊的x和y創建一個矩形。但是,它將矩形放在一邊一些,我不知道爲什麼。爲什麼我在這個畫布上創建的矩形沒有放在正確的位置?

小提琴:https://jsfiddle.net/2717s53h/

HTML

<canvas id="cnv"></canvas> 

CSS

#cnv{ 
    width:99vw; 
    height:98vh; 
    background-color:#faefbd; 
} 

JAVASCRIPT

$(function() { 
    var canvas = $('#cnv'); 
    var canvObj = document.getElementById('cnv'); 
    var ctx = canvObj.getContext('2d'); 

    var point1 = {}; 
    var point2 = {}; 

    canvas.click(function (e) { 
     console.log(e); 

     var x = e.pageX; 
     var y = e.pageY; 

     console.log(x); 
     console.log(y); 

     if (Object.keys(point1).length == 0) 
     { 
      point1.x = x; 
      point1.y = y; 
     } 
     else if (Object.keys(point2).length == 0) 
     { 
      point2.x = x; 
      point2.y = y; 

      console.log(point1); 
      console.log(point2); 
      var width = point2.x - point1.x; 
      var height = point2.y - point1.y; 
      width = width < 0 ? width * -1 : width; 
      height = height < 0 ? height * -1 : height; 
      ctx.fillRect(x, y, 10, 10); 

      point1 = {}; 
      point2 = {}; 
     } 

    }); 
}); 
+0

可能重複的[HTML5 JS fillRect()奇怪的行爲](http://stackoverflow.com/questions/13557429/html5-js-fillrect-strange-behavior) – ieaglle

回答

3

CSS高度/寬度與HTML畫布屬性高度和寬度之間存在差異:前者定義畫布在頁面中佔用的空間;後者定義了渲染表面。在concreto,假設你有以下帆布:

<canvas height="400" width="600"></canvas> 

具有1200x800大小的視口和畫布CSS設置爲width: 100%; height: 100%;,那麼你的畫布,將呈現爲伸出兩倍大和模糊的無論高度還是寬度(就像在你的小提琴中;顯然那些矩形大於10px)。因此,頁面座標不與畫布的座標同步。

按照該specification,你撥弄的畫布渲染表面是300x150,因爲你沒有指定寬度/高度屬性:

width屬性默認爲300,height屬性默認爲150

查看your fiddle的稍微'更正'的版本。

因此,我的建議(作爲非HTML-canvas專家)將是總是指定這兩個屬性,而不是混淆不同的渲染表面與顯示尺寸(當然不是相對的像vw, vh,%,em,...),如果你不想要不可預知的結果;儘管一些SO用戶一直在尋找a solution

+0

謝謝!我不知道。 – Jesse

相關問題