How to draw a smooth continuous line with mouse using html canvas and javascript

前端 未结 3 1547
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 23:39

I\'m attempting to create a simple draw/paint programme using html5 canvas and plain javascript. I\'ve got it working ok, but when drawing and moving the mouse too fast the

3条回答
  •  甜味超标
    2020-12-09 00:21

    You could save the last position and draw a line between the last point and the actual point.

    if (lastX && lastY && (x !== lastX || y !== lastY)) {
        ctx.fillStyle = "#000000";
        ctx.lineWidth = 2 * size;
        ctx.beginPath();
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(x, y);
        ctx.stroke();
        // ...
       lastX = x;
       lastY = y;
    }
    

    On mouseup event set the two variables to zero.

    var canvas, ctx
    var mouseX, mouseY, mouseDown = 0,
        lastX, lastY;
    
    function draw(ctx,x,y,size) {
        if (lastX && lastY && (x !== lastX || y !== lastY)) {
            ctx.fillStyle = "#000000";
            ctx.lineWidth = 2 * size;
            ctx.beginPath();
            ctx.moveTo(lastX, lastY);
            ctx.lineTo(x, y);
            ctx.stroke();
        }
      ctx.fillStyle = "#000000";
      ctx.beginPath();
      ctx.arc(x, y, size, 0, Math.PI*2, true);
      ctx.closePath();
      ctx.fill();
      lastX = x;
      lastY = y;
    }
    
    function clearCanvas(canvas,ctx) {
      ctx.clearRect(0, 0, canvas.width, canvas.height)
    }
    
    function onMouseDown() {
      mouseDown = 1
      draw(ctx, mouseX, mouseY, 2)
    }
    
    function onMouseUp() {
      mouseDown = 0;
      lastX = 0;
      lastY = 0;
    }
    
    function onMouseMove(e) {
      getMousePos(e)
      if (mouseDown == 1) {
          draw(ctx, mouseX, mouseY, 2)
      }
    }
    
    function getMousePos(e) {
      if (!e)
          var e = event
      if (e.offsetX) {
          mouseX = e.offsetX
          mouseY = e.offsetY
      }
      else if (e.layerX) {
          mouseX = e.layerX
          mouseY = e.layerY
      }
     }
    
    function init() {
        canvas = document.getElementById('sketchpad')
        ctx = canvas.getContext('2d')
        canvas.addEventListener('mousedown', onMouseDown, false)
        canvas.addEventListener('mousemove', onMouseMove, false)
        window.addEventListener('mouseup', onMouseUp, false)
    }
    
    init();

提交回复
热议问题