Mouse Drag on a Disk


this code is created first by chatGPT on Jan 10 2023 (meaning using chatGPT 3.5) and then modified a little bit my me. The initial request that I put into chatGPT is as follows :


Write a javascript with the following requirement

1. create a table at the center of the page

2. the table has only one cell, make grid visible in thin line

3. put a canvas with the size of 400x400 pixel in the cell

4. draw a circle at the center of the canvas, filled with red color

5. make the circle draggable by mouse pointer

6. separate html part and javascript part into separate files

NOTE : It is not guaranteed that you would have the same code as I got since chatGPT produce the answers differently depending on the context. And it may produce the different answers everytime you ask even with the exact the same question.

NOTE : If you don't have any of your own idea for the request, copy my request and paste it into the chatGPT and put additional requests based on the output for the previous request. I would suggest to create a new thread in the chatGPT and put my request and then continue to add your own request.




<!DOCTYPE html>



    <title>Table with Canvas</title>



    <table align="center">



          <canvas id="myCanvas" width="400" height="400"></canvas>




    <script src="mousedrag_disk.js"></script>






const canvas = document.getElementById('myCanvas');

const ctx = canvas.getContext('2d');


let isDragging = false;

let currentX = canvas.width/2;

let currentY = canvas.height/2;

let initialX = currentX;

let initialY = currentY;

let xOffset = currentX;

let yOffset = currentY;


canvas.addEventListener("mousedown", dragStart);

canvas.addEventListener("mouseup", dragEnd);

canvas.addEventListener("mousemove", drag);


function dragStart(e) {

  initialX = e.clientX - xOffset;

  initialY = e.clientY - yOffset;


  if ( === canvas) {

    isDragging = true;





function dragEnd(e) {

  initialX = currentX;

  initialY = currentY;


  isDragging = false;



function drag(e) {

  if (isDragging) {


    currentX = e.clientX - initialX;

    currentY = e.clientY - initialY;


    xOffset = currentX;

    yOffset = currentY;




    // Print the distance value at the top left corner of the canvas

    ctx.font = "16px Arial";

    ctx.fillStyle = "black";

    ctx.textAlign = "left";

    ctx.fillText(`Current position: (${currentX}, ${currentY})`, 10, 20);





function draw() {

  ctx.clearRect(0, 0, canvas.width, canvas.height);


  ctx.arc(currentX, currentY, 50, 0, Math.PI * 2, false);

  ctx.fillStyle = "red";


  ctx.strokeStyle = "black";

  ctx.strokeRect(0, 0, canvas.width, canvas.height);