2017-04-06 138 views
1

我在畫布上寫文字並畫一條線。不知怎的,我結束了在我的畫布不必要的邊界:畫布周圍不需要的邊框

enter image description here

首先,我寫在右上角的文本,並呼籲context.save(),然後我劃清界線,並呼籲context.stroke()

代碼:

$(document).ready(function() { 
    var canvas = document.getElementById('canvas'); 
    var context = canvas.getContext('2d'); 

    context.beginPath(); 
    context.rect(0, 0, canvas.width, canvas.height); 
    context.fillStyle = 'black'; 
    context.fill(); 

    paintName(context, canvas); 
    drawLine(context); 
}); 



function paintName(context, canvas) { 

    context.textAlign = "left"; 
    context.font = "16pt Arial"; 
    context.fillStyle = 'red'; 
    context.fillText('G5', context.canvas.width - 35, 18); 
    context.strokeStyle = 'red'; 

    context.save(); 
} 

function drawLine(context){ 
    var gatingCoords = [[30, 120], [50, 300]]; 
    var nextX, nextY, pointX, pointy; 

    context.lineWidth = 4; 

    for (var i = 0; i < gatingCoords.length; i++) { 

     pointX = gatingCoords[i][0]; 
     pointY = gatingCoords[i][1]; 


     if (i === gatingCoords.length - 1) { 
      nextX = gatingCoords[0][0]; 
      nextY = gatingCoords[0][1]; 
     } else { 
      nextX = gatingCoords[i + 1][0]; 
      nextXY = gatingCoords[i + 1][1]; 
     } 

     context.moveTo(pointX, pointY); 
     context.lineTo(nextX, nextY); 
    } 

    context.stroke(); 
} 

和小提琴是here。這是怎麼發生的?

+0

可能的[刪除HTML畫布邊框]的副本(http://stackoverflow.com/questions/14042938/remove-html-canvas-border) –

+0

您需要重置默認瀏覽器樣式,因爲瀏覽器提供了一些默認的邊距和填充。 [查看這個dup問題的詳細信息](http://stackoverflow.com/a/14042964/3931488)。 –

+0

但邊界是在圖像上....右擊並下載,你會看到它的PNG – Mark

回答

1

邊界來自context.rect(0,0,canvas.width,canvas.height)。如果在paintName(context,canvas)之前添加另一個context.beginPath(),則邊框將消失。

1

問題是我沒有使用context.beginPath();之前moveTo()

context.beginPath(); 
    context.moveTo(pointX, pointY); 
    context.lineTo(nextX, nextY); 
    context.stroke();