画布周围不需要的边框

时间:2017-04-06 13:12:48

标签: javascript css html5 canvas

我在画布上写文字并画一条线。不知何故,我的画布周围出现了一个不需要的边框:

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。这是怎么回事?

3 个答案:

答案 0 :(得分:1)

问题是我没有使用context.beginPath();在moveTo()之前,即

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

答案 1 :(得分:1)

希望这会对你有所帮助。

drawLine功能中,添加第context.beginPath();

https://www.w3schools.com/tags/canvas_beginpath.asp

答案 2 :(得分:1)

边框来自context.rect(0,0,canvas.width,canvas.height)。如果你在paintName(context,canvas)之前添加另一个context.beginPath(),那么边框就会消失。