Q: drag and drop a pawn in a canvas in JavaScript I'm doing a Web page role play like DnD. I did a canvas to draw the map, and I want to have an option to drag and drop a pawn in the map to represent the player. But I don't know how to do that. I was thinking about create a circle ctx.arc() and clear when it's move, but it will erase the map too. How can I do it ?


window.onload = function()
{
    const canvas = document.getElementById("myCanvas");
    const ctx = canvas.getContext('2d');
    //const ctx2 = canvas.getContext('2d')
    canvas.height = 500;
    canvas.width = 700;

    let painting = false;
    let penUsed = true;
    let eraser = false;

    document.getElementById('pen').onclick = function () {
        if (!penUsed) {
            penUsed = true;
            eraser = false;
        } else penUsed = false;
    }


    document.getElementById('erase').onclick = function () {
        if (!eraser) {
            eraser = true;
            penUsed = false;
        } else eraser = false
    }

    function startDraw() {
        painting = true;
    }

    function endDraw() {
        painting = false;
        ctx.beginPath();
    }

    function drawOrErase(e) {
        if (!painting) return;
        if (penUsed) draw(e);
        if (eraser) erase(e);
    }

    function draw(e) {
        ctx.lineJoin = 'round';
        ctx.lineCap = 'round';
        ctx.lineTo(e.pageX-10, e.pageY-10);
        ctx.stroke();
    }

    function erase(e) {
        ctx.clearRect(e.pageX-10, e.pageY-10, 20, 20);
    }

    document.addEventListener('mousedown', startDraw);
    document.addEventListener('mouseup', endDraw);
    canvas.addEventListener('mousemove', drawOrErase);
}
<html>
<head>

    <script src="stackOver.js"></script>
</head>
<body>
    <canvas id="myCanvas"></canvas>
    <label for="pen">Pen</label>
    <input type="radio" name="pen" checked id="pen">
    <label>Eraser</label>
    <input type="radio" name="pen" id="erase">
</body>
<style>
    #myCanvas{
        background-color: white;
        border: 2px solid black;
        cursor: crosshair;
    }
</style>
<script src="stackOver.js"></script>
</html>


