2013-01-17 38 views
2

我試圖通過拖動鼠標繪製一個矩形,基本上遵循此tutorial寬度在px中指定或不更改畫布行爲

但是,我發現如果我在px中指定畫布尺寸,它將不起作用。相反,如果我用這個網站,這工作得很好:

<!DOCTYPE html> 
<html> 

<head> 
    <title>drag a rectangle</title> 

    <style> 
    #cvs { 
     width: 500; 
     height: 500; 
     border: 1px solid #666; 
    } 
    </style> 

    <script src="jquery-1.9.0.js"></script> 
</head> 

<body> 
    <canvas id="cvs"></canvas> 

    <script src="main.js"></script> 
</body> 

</html> 

而且這個js:

$(document).ready(function() { 
    var canvas = document.getElementById('cvs'); 
    var ctx = canvas.getContext('2d'); 
    var rect = {}; 
    var drag = false; 

    var mouseDown = function(e) { 
     rect.startX = e.pageX - this.offsetLeft; 
     rect.startY = e.pageY - this.offsetTop; 
     console.log(rect.startX + ' ' + rect.startY); 
     drag = true; 
    }; 

    var mouseUp = function(e) { 
     drag = false; 
    }; 

    var draw = function() { 
     ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h); 
    }; 

    var mouseMove = function(e) { 
     if (drag) { 
      rect.w = (e.pageX - this.offsetLeft) - rect.startX; 
      rect.h = (e.pageY - this.offsetTop) - rect.startY; 
      console.log(rect.w + ' ' + rect.h); 
      ctx.clearRect(0, 0, canvas.width, canvas.height); 
      draw(); 
     } 
    }; 

    function init() { 
     canvas.addEventListener('mousedown', mouseDown, false); 
     canvas.addEventListener('mouseup', mouseUp, false); 
     canvas.addEventListener('mousemove', mouseMove, false); 
    } 

    init(); 
}); 

它工作正常。然而,如果我指定的尺寸在px,即

#cvs { 
    width: 500px; 
    height: 500px; 
    border: 1px solid #666; 
} 

鼠標位置和矩形不再對齊。而且,視口中的維度也不同。我認爲這是一個基本問題,但是指定px還是沒有區別?那這怎麼影響我的拖動矩形行爲?

本地測試最新的Chrome。

回答

2

要設置畫布的大小,請使用畫布元素屬性widthheight

<canvas width="400" height="300">Not supported</canvas> 

在頁面加載時畫布大小設置爲它的widthheight。如果設置了style.width和/或style.height,畫布將縮放以適應這些樣式中指定的尺寸。

Here就是一個例子。

所以現在你的問題。正如我在設置style.widthstyle.height如上面寫道:

#cvs { 
    width: 500px; 
    height: 500px; 
    border: 1px solid #666; 
} 

的寬度和高度將適用於畫布將擴展它的大小,讓你想到哪裏座標(x, y)點不會出現。例如,如果您嘗試繪製座標爲(500, 500)的點,則可能根本看不到它,因爲只是您的畫布座標系的尺寸小於此尺寸。當你沒有指定px時,你只是不提供有效的寬度和高度,並且你的樣式不能正確應用,所以你的畫布沒有縮放,一切都按照你的預期工作。

+0

謝謝。但我的問題是'400px'和'400'之間有什麼區別,以及這會如何影響我的鼠標拖動行爲。 – clwen

+0

看看我的版本。 –

+1

所以,如果你縮放你的座標,一切都會很好......除了模糊效果(或缺陷...)。最好不要在畫布上使用'style.width \ height'。 –