JSFiddle - React, Tailwind, and code Playground
by pedro_g_s
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Whiteboard with Gradient Line</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
canvas {
border: 2px solid #000;
}
</style>
</head>
<body>
<canvas id="whiteboard" width="800" height="600"></canvas>
<script>
const canvas = document.getElementById('whiteboard');
const ctx = canvas.getContext('2d');
let drawing = false;
function startDrawing(e) {
drawing = true;
draw(e);
}
function endDrawing() {
drawing = false;
ctx.beginPath(); // Reset path so lines don't connect
}
function draw(e) {
if (!drawing) return;
// Get mouse position relative to the canvas
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
// Create a linear gradient from red to blue
const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'blue');
// Set gradient stroke style
ctx.strokeStyle = gradient;
ctx.lineWidth = 5; // Set line width
ctx.lineCap = 'round'; // Smooth line edges
// Start drawing
ctx.lineTo(x, y);
ctx.stroke();
// Reset the path to avoid the line joining
ctx.beginPath();
ctx.moveTo(x, y);
}
// Mouse event listeners
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mouseup',...