JSFiddle - React, Tailwind, and code Playground
by Julien Etienne
HTML
<canvas id="myCanvas" width="400" height="300"></canvas>
CSS
canvas {
border: 1px solid #ccc;
}
JavaScript
// Get the canvas and context
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Load the image
const img = new Image();
img.src = 'path/to/your/image.jpg';
// When the image is loaded, draw it with rounded corners and shadow
img.onload = function() {
// Draw the shadow first
ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
ctx.shadowBlur = 10;
ctx.shadowOffsetX = 5;
ctx.shadowOffsetY = 5;
// Draw a rectangle with rounded corners (shadow only)
ctx.beginPath();
ctx.roundRect(20, 20, canvas.width - 40, canvas.height - 40, 20);
ctx.fillStyle = 'red'; // Set the fill color to match the canvas background
ctx.fill();
// Reset shadow
ctx.shadowColor = 'transparent';
ctx.shadowBlur = 0;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
// Draw the image with rounded corners
ctx.beginPath();
ctx.roundRect(20, 20, canvas.width - 40, canvas.height - 40, 20);
ctx.clip(); // Apply the clip path
ctx.drawImage(img, 20, 20, canvas.width - 40, canvas.height - 40);
ctx.resetClip(); // Reset clip path
};
// Utility function to draw a rectangle with rounded corners
CanvasRenderingContext2D.prototype.roundRect = function (x, y, width, height, radius) {
this.moveTo(x + radius, y);
this.arcTo(x + width, y, x + width, y + height, radius);
this.arcTo(x + width, y + height, x, y + height, radius);
this.arcTo(x, y + height, x, y, radius);
this.arcTo(x, y, x + width, y, radius);
};