【问题标题】:How to keep drawing on canvas when scrolling?滚动时如何在画布上继续绘图?
【发布时间】:2021-02-01 13:55:41
【问题描述】:

我想实现画布作为我网站的背景,以便用户可以使用光标在网页上绘画,就像这个 codepen:https://codepen.io/cocotx/pen/PoGRdxQ?editors=1010 (这是来自http://www.dgp.toronto.edu/~clwen/test/canvas-paint-tutorial/的示例代码)

if(window.addEventListener) {
window.addEventListener('load', function () {
  var canvas, context;

  // Initialization sequence.
  function init () {
    // Find the canvas element.
    canvas = document.getElementById('imageView');
    if (!canvas) {
      alert('Error: I cannot find the canvas element!');
      return;
    }

    if (!canvas.getContext) {
      alert('Error: no canvas.getContext!');
      return;
    }

    // Get the 2D canvas context.
    context = canvas.getContext('2d');
    if (!context) {
      alert('Error: failed to getContext!');
      return;
    }

    // Attach the mousemove event handler.
    canvas.addEventListener('mousemove', ev_mousemove, false);
  }

  // The mousemove event handler.
  var started = false;
  function ev_mousemove (ev) {
    var x, y;

    // Get the mouse position relative to the canvas element.
    if (ev.layerX || ev.layerX == 0) { // Firefox
      x = ev.layerX;
      y = ev.layerY;
    } else if (ev.offsetX || ev.offsetX == 0) { // Opera
      x = ev.offsetX;
      y = ev.offsetY;
    }

    // The event handler works like a drawing pencil which tracks the mouse 
    // movements. We start drawing a path made up of lines.
    if (!started) {
      context.beginPath();
      context.moveTo(x, y);
      started = true;
    } else {
      context.lineTo(x, y);
      context.stroke();
    }
  }

  init();
}, false); }

问题是当我滚动时光标停止绘画,直到我再次移动鼠标。关于如何在滚动时保持光标绘制的任何想法?

提前致谢!非常感谢!

【问题讨论】:

    标签: javascript canvas html5-canvas


    【解决方案1】:

    您必须存储最后一个鼠标事件并在滚动事件中触发一个新的

    幸运的是,MouseEvent constructor 接受一个 mouseEventInit 对象,我们可以在该对象上设置新事件的 clientXclientY 值,因此我们只需要存储之前的这些值事件并在 scroll 事件中调度它。

    现在,我忍不住用您的代码重写了几乎所有内容。
    它对旧浏览器进行了大量检查(比如非常旧的浏览器,无论如何都不应该再次面对网络),如果你愿意,你可能想再次添加它。
    它并没有清除上下文,这意味着每次它画一条新线时,它也确实在自身上重新画了之前的线,导致线条更粗,开头有很多噪音,结尾更流畅。
    这可以通过多种方式解决,干扰较小的一种是在每一帧清除上下文。 为了获得相对鼠标位置,它现在使用事件的 clientX 和 clientY 属性。

    其余的更改在 sn-p 中注释。

    window.addEventListener('load', function () {
      const canvas = document.getElementById('imageView');
      context = canvas.getContext("2d");
      let last_event; // we will store our mouseevents here
      
      // we now listen to the mousemove event on the document,
      // not only on the canvas
      document.addEventListener('mousemove', ev_mousemove);
      document.addEventListener('scroll', fireLastMouseEvent, { capture: true } );
      // to get the initial position of the cursor
      // even if the mouse never moves
      // we listen to a single mouseenter event on the document's root element
      // unfortunately this seems to not work in Chrome
      document.documentElement.addEventListener( "mouseenter", ev_mousemove, { once: true } );
    
      // called in scroll event
      function fireLastMouseEvent() {
        if( last_event ) {
          // fire a new event on the document using the same clientX and clientY values
          document.dispatchEvent( new MouseEvent( "mousemove", last_event ) );
        }
      }
      
      // mousemove event handler.
      function ev_mousemove (ev) {
        const previous_evt = last_event || {};
        const was_offscreen = previous_evt.offscreen;
        
        // only for "true" mouse event
        if( ev.isTrusted ) {
          // store the clientX and clientY props in an object
          const { clientX, clientY } = ev;
          last_event = { clientX, clientY };
        }
        
        // get the relative x and y positions from the mouse event
        const point = getRelativePointFromEvent( ev, canvas );
        
        // check if we are out of the canvas viewPort
        if( point.x < 0 || point.y < 0 || point.x > canvas.width || point.y > canvas.height ) {
          // remember we were
          last_event.offscreen = true;
          // if we were already, don't draw
          if( was_offscreen ) { return; }
        }
        // we come from out-of-screen to in-screen
        else if( was_offscreen ) { 
          // move to the previous point recorded as out-of-screen
          const previous_point = getRelativePointFromEvent( previous_evt, canvas );
          context.moveTo( previous_point.x, previous_point.y );
        }
        
        // add the new point to the context's sub-path definition
        context.lineTo( point.x, point.y );
    
        // clear the previous drawings
        context.clearRect( 0, 0, canvas.width, canvas.height );
        // draw everything again
        context.stroke();
    
      }
    
      function getRelativePointFromEvent( ev, elem ) {
        // first find the bounding rect of the element
        const bbox = elem.getBoundingClientRect();
        // subtract the bounding rect from the client coords
        const x = ev.clientX - bbox.left;
        const y = ev.clientY - bbox.top;
    
        return { x, y };
      }
    });
    #container {
      width: 400px;
      height: 200px;
      overflow: auto;
      border: 1px solid;
    }
    #imageView { border: 1px solid #000; }
    canvas {
      margin: 100px;
    }
    <div id="container">
      <canvas id="imageView" width="400" height="300"></canvas>
    </div>

    【讨论】:

    • 嗨 Kaiido,这是完美的,非常感谢!并感谢您的详细解释!但是,如果用户在不移动鼠标的情况下直接开始滚动,我应该从您的代码中更改什么以确保光标也会绘制?
    • 或者在用户移动之前浏览器是否无法获取鼠标位置?
    • @CocoYuan 我认为您应该能够收听mouseenter事件,我认为应该在页面加载时触发 documentElement .它在 Safari 和 Firefox 中这样做,但在 Chrome 中却没有,我们显然不走运,因为在这个浏览器中,他们甚至看不到 documentElement 是 :hover,直到鼠标移动。
    • 嗨 Kaiido,这是很棒的工作代码,但由于画布,我的网站性能遇到了问题。我使用这个画布作为我的一页网站的背景,这个网站很长,我注意到在网站上一段时间后绘图变得缓慢和滞后。所以我想知道我们是否可以做这样的事情:donotdrawapenis.com(如果你继续画,你会看到它只画了固定长度的线),因为这可能有助于它的性能?谢谢!我想我也会为此提出另一个问题。
    • 当鼠标在画布外时,您可以添加简单的检查以避免绘制是的,如果我有时间我明天再编辑。
    猜你喜欢
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    相关资源
    最近更新 更多