滚动时如何继续在画布上绘图?

如何解决滚动时如何继续在画布上绘图?

我想将画布作为我网站的背景,这样用户就可以使用他们的光标在网页上绘画,就像这样的代码笔: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); }

问题是当我滚动时光标停止绘制,直到我再次移动鼠标。知道如何在滚动时保持光标绘画吗?

提前致谢!非常感谢!

解决方法

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

幸运的是,MouseEvent constructor 接受一个 mouseEventInit 对象,我们可以在该对象上设置新事件的 clientXclientY 值,因此我们只需要存储来自前一个事件的这些值并将其分派到 scroll 事件中。

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

其余的更改在代码段中进行了注释。

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,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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res