如何在画布周围画边框

7

我正在画一个白色背景的画布,想要在画布周围画一个边框,但我无法实现。以下是我的代码:

canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext('2d');
context.fillStyle = "black";
context.font = "50px Arial";
context.fillText(chartId, 0, 50);
context.drawImage(image, 0, 0);
context.globalCompositeOperation = "destination-over";
context.fillStyle = "#FFFFFF";
context.fillRect(0,0,canvas.width,canvas.height);//for white background

在此之后,我希望整个画布周围出现红色的边框。

@blex好像没起作用,我看不到边框。 - ValarDohaeris
1
好的,canvas.style.border = '1px solid red'; 只是在画布周围添加了一个 CSS 边框,而不是在画布上绘制它。在此处查看演示 - blex
1个回答

8

context.lineWidth 设置为 2,将 context.strokeStyle 设置为 #FF0000,并使用 context.strokeRect,而不是 fillRect。 如果 globalCompositeOperation 设置为 destination-over,则新应用的内容将使用画布的值,所以改为 source-over。在您的代码中使用 lightblue 来模拟 drawImage

var canvas = document.getElementById('cv');
canvas.width = 400;
canvas.height = 300;
var context = canvas.getContext('2d');
context.fillStyle = "black";
context.font = "50px Arial";
context.fillText('ASD', 0, 50);
context.globalCompositeOperation = "destination-over";
context.fillStyle = "#00FFFF";
context.fillRect(0,0,canvas.width,canvas.height);//for white background
context.globalCompositeOperation = "source-over";
context.lineWidth = 2;
context.strokeStyle="#FF0000";
context.strokeRect(0, 0, canvas.width, canvas.height);//for white background
<canvas id="cv"></canvas>


如果我想要添加边框轮廓怎么办? 例如:宽度:100 高度:100 边框宽度:5 最终尺寸:宽度:110 高度:110提前感谢, Chris Pappas - Chris P
@ChrisP 我不确定我理解你的问题,如果你的意思是想在画布外面加上边框,为什么不直接使用 CSS 边框呢。例如:https://jsfiddle.net/vczf4tye/ - fuyushimoya
1
@fuyushimoya,问题是,如果您需要将画布内容下载为图像,则边框不会被包括在内。 - innovaciones

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接