Very simply, you need to ensure you are drawing the text over the stroke you are drawing, in the example below using fillText()
.
Notice in the draw
function there is now text being painted.
const canvas = document.getElementById('drawing-board');
const ctx = canvas.getContext('2d');
const canvasOffsetX = canvas.offsetLeft;
const canvasOffsetY = canvas.offsetTop;
canvas.width = window.innerWidth - canvasOffsetX;
canvas.height = window.innerHeight - canvasOffsetY;
let isPainting = true;
let lineWidth = 100;
let startX;
let startY;
const colour = "black";
ctx.strokeStyle = "black"
ctx.fillStyle= "transparent";
ctx.font = "italic bold 15pt Tahoma";
// ctx.strokeText("StackOverFlow",100,240);
// ctx.strokeStyle = colour;
const draw = (e) => {
if(!isPainting) {
return;
}
ctx.lineWidth = lineWidth;
ctx.lineCap = 'round';
ctx.lineTo(e.clientX - canvasOffsetX, e.clientY);
ctx.stroke();
// Drawn after (over) the stroke with white
ctx.fillStyle = "white"; // <--
ctx.fillText("StackOverFlow", 20, 50); // <-- todo: hardcoded position
}
canvas.addEventListener('mousedown', (e) => {
isPainting = false;
startX = e.clientX;
startY = e.clientY;
});
canvas.addEventListener('mouseup', e => {
isPainting = true;
ctx.stroke();
ctx.beginPath();
});
canvas.addEventListener('mousemove', draw);
<body>
<section class="container">
<div class="drawing-board">
<canvas id="drawing-board"></canvas>
</div>
</section>
<script src="./index.js"></script>
</body>
Additionally, I have hardcoded the text position to display on StackOverflow (in the top-left corner), you may want to create some logic to move it where needed.