How to draw a image with circular border in canvas?

by mallory_cormier , in category: Javascript , 5 months ago

How to draw a image with circular border in canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 5 months ago

@mallory_cormier 

To draw an image with a circular border in canvas, you can use the following steps:

  1. Create a canvas element in your HTML file:
1
<canvas id="myCanvas" width="300" height="300"></canvas>


  1. Get the canvas element and its context in your JavaScript file:
1
2
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');


  1. Create a new Image object and set its source:
1
2
var img = new Image();
img.src = 'myImage.jpg';


  1. Once the image is loaded, draw it on the canvas with a circular border:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
img.onload = function() {
    ctx.save();
    ctx.beginPath();
    ctx.arc(canvas.width / 2, canvas.height / 2, 100, 0, Math.PI * 2);
    ctx.clip();
    ctx.drawImage(img, canvas.width / 2 - 100, canvas.height / 2 - 100, 200, 200);
    ctx.closePath();
    ctx.lineWidth = 5;
    ctx.strokeStyle = 'black';
    ctx.stroke();
    ctx.restore();
};


  1. Add some CSS styling to center the canvas on the page and give it a border:
1
2
3
4
5
#myCanvas {
    display: block;
    margin: 0 auto;
    border: 1px solid black;
}


  1. Finally, add the necessary image file to your project and run your HTML file in a browser to see the image with a circular border drawn on the canvas.