0

I am trying onmousemove event js but I some issue I didn't solve, need to clear solution.

I have make onmousemove event but I need to control this speed how far it's speed. I need each span append tag should stuck each other like plain drawing no need any space among the span append tag. please see my snippet below for clear idea which I wanted.

document.onmousemove = doMove;



  function doMove(e){
  let body = document.querySelector('body');
  let span = document.createElement('span');
  let x = e.clientX;
  let y = e.clientY;
  body.appendChild(span);
  span.style.left = x + 'px';
  span.style.top = y + 'px';
}
span{
  width: 15px;
  height: 15px;
  position: absolute;
  background: red;
  transition: .1s;
}
NIKHIL CHANDRA ROY
  • 807
  • 11
  • 16

1 Answers1

0

As this answer noted, you can't control the frequency of mousemove event -- it depends on the browser and device you're on.

I suggest using a canvas. One solution can be found here: https://codepen.io/zsolt555/pen/rpPXOB.

// ...
const stopDrawing = () => { isMouseDown = false; }
const startDrawing = event => {
    isMouseDown = true;   
   [x, y] = [event.offsetX, event.offsetY];  
}
const drawLine = event => {
    if ( isMouseDown ) {
        const newX = event.offsetX;
        const newY = event.offsetY;
        context.beginPath();
        context.moveTo( x, y );
        context.lineTo( newX, newY );
        context.stroke();
        //[x, y] = [newX, newY];
        x = newX;
        y = newY;
    }
}

paintCanvas.addEventListener( 'mousedown', startDrawing );
paintCanvas.addEventListener( 'mousemove', drawLine );
paintCanvas.addEventListener( 'mouseup', stopDrawing );
paintCanvas.addEventListener( 'mouseout', stopDrawing );
technophyle
  • 7,972
  • 6
  • 29
  • 50