简体   繁体   English

画布周围不需要的边框

[英]Unwanted border around canvas

Im writing text on a canvas and drawing a line. 我在画布上写文字并画一条线。 Somehow, I end up with an unwanted border around my canvas: 不知何故,我最终在画布周围出现了一个不需要的边框:

在此输入图像描述

First I write the text in top right corner and call context.save() , then i draw the line and call context.stroke() . 首先,我在右上角写文本并调用context.save() ,然后我画线并调用context.stroke()

Code: 码:

$(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();
}

And fiddle is here . 小提琴在这里 How is this happening? 这是怎么回事?

The issue was I wasnt using context.beginPath(); 问题是我没有使用context.beginPath(); before moveTo() ie moveTo()之前

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

Hope this will help you. 希望这会帮助你。

In drawLine function, add the line context.beginPath(); drawLine函数中,添加行context.beginPath();

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

The border comes from context.rect(0, 0, canvas.width, canvas.height). 边框来自context.rect(0,0,canvas.width,canvas.height)。 If you add another context.beginPath() right before paintName(context, canvas), then the border goes away. 如果在paintName(context,canvas)之前添加另一个context.beginPath(),则边框将消失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM