How to draw a border around the canvas

I am drawing an image on a canvas with a white background. I want to draw a border around the canvas and I cannot do that. Here is my code:

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

      

after that i want the red border to appear around the whole canvas.

+3


source to share


1 answer


Install context.lineWidth

in 2

, install context.strokeStyle

on #FF0000"

and use context.strokeRect

, not fillRect

. globalCompositeOperation

if set to value destination-over

then the new thing will apply the canvas value so change to source-over

. Used lightblue

to spoof drawImage

in your code



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>
      

Run code


+3


source







All Articles