如何在画布周围绘制边框

Val*_*ris 6 html javascript canvas

我正在用白色背景色在画布上绘制图像。我想在画布周围画一个边框,但我无法这样做。这是我的代码:

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
Run Code Online (Sandbox Code Playgroud)

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

fuy*_*oya 6

设置context.lineWidth2,设置context.strokeStyle#FF0000",并使用context.strokeRect,而不是fillRectglobalCompositeOperation如果设置为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
Run Code Online (Sandbox Code Playgroud)
<canvas id="cv"></canvas>
Run Code Online (Sandbox Code Playgroud)