2014-09-22 77 views
1

我有這個設置矩形的簡單代碼。將真實顏色設置爲畫布邊框筆劃?

我正在用黑色撫摸它的邊框。

但是,我沒有在這裏看到任何黑色,但灰色。

<!doctype html> 
 
<html lang="en"> 
 

 
<canvas id="canvas" width=300 height=300></canvas> 
 

 
<script> 
 
function draw() 
 
{ 
 
    ctx.beginPath(); 
 
    ctx.strokeStyle = "#000000"; 
 
    ctx.strokeRect(rect.x, rect.y, rect.w, rect.h); 
 
} 
 
var canvas = document.getElementById("canvas"); 
 
var ctx = canvas.getContext("2d"); 
 
ctx.clearRect(0, 0, canvas.width, canvas.height); 
 
var rect = { 
 
    x: 10, 
 
    y: 10, 
 
    w: 40, 
 
    h: 100 
 
}; 
 
draw(); 
 
</script> 
 

 
</html>

問:

什麼我做錯了,我怎麼可以設置顏色要爲我定義?

+0

可能重複[在html5畫布中繪製單個像素行](http://stackoverflow.com/questions/9311428/draw-single-pixel-line-in-html5- canvas) – 2014-09-22 12:35:05

+0

重複 - http://stackoverflow.com/questions/9311428/draw-single-pixel-line-in-html5-canvas – 2014-09-22 12:35:14

回答

1

當您創建一條畫布線時,它將使一條線通過您聲明的點,寬度爲lineWidth。如果線條在2個像素之間(例如,當您創建一條穿過邊框的線條,意味着您爲x和y選擇整數值),它會消除顏色以平衡線條所穿過的2個像素,在這種情況下爲50%左邊的像素和右邊的像素的50%,導致灰色。 添加.5你的x和y使該行始終停留在1個像素

<!doctype html> 
 
<html lang="en"> 
 

 
<canvas id="canvas" width=300 height=300></canvas> 
 

 
<script> 
 
function draw() 
 
{ 
 
    ctx.beginPath(); 
 
    ctx.strokeStyle = "#000000"; 
 
    ctx.strokeRect(rect.x, rect.y, rect.w, rect.h); 
 
} 
 
var canvas = document.getElementById("canvas"); 
 
var ctx = canvas.getContext("2d"); 
 
ctx.clearRect(0, 0, canvas.width, canvas.height); 
 
var rect = { 
 
    x: 10.5, 
 
    y: 10.5, 
 
    w: 40, 
 
    h: 100 
 
}; 
 
draw(); 
 
</script> 
 

 
</html>

如果您運行的片斷,你會看到線條是直的黑,只佔用1個像素寬度。我剛剛添加了.5到你的x和y