[英]HTML5 canvas drawing board - touch support
I am using this simple script to enable users to enter their signatures.我正在使用这个简单的脚本来使用户能够输入他们的签名。 Unfortunately, this does not work on mobile devices.不幸的是,这不适用于移动设备。
var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var container = document.getElementById('container'); var container_style = getComputedStyle(container); canvas.width = 400; canvas.height = 300; var mouse = {x: 0, y: 0}; canvas.addEventListener('mousemove', function(e) { mouse.x = e.pageX - this.offsetLeft; mouse.y = e.pageY - this.offsetTop; }, false); ctx.lineJoin = 'round'; ctx.lineCap = 'round'; ctx.strokeStyle = "black"; function getSize(size){ctx.lineWidth = size;} canvas.addEventListener('mousedown', function(e) { ctx.beginPath(); ctx.moveTo(mouse.x, mouse.y); canvas.addEventListener('mousemove', onPaint, false); }, false); canvas.addEventListener('mouseup', function() { canvas.removeEventListener('mousemove', onPaint, false); }, false); var onPaint = function() { ctx.lineTo(mouse.x, mouse.y); ctx.stroke(); };
#canvas { border: 1px solid rgba(0,0,0,.5); }
<div id="container"> <canvas id="canvas"></canvas> </div>
Is there an easy way to add touch support to this script?有没有一种简单的方法可以为这个脚本添加触摸支持?
Make these changes to your code:对您的代码进行以下更改:
pointerdown
, pointerup
, and pointermove
.使用指针事件(而不是鼠标事件): pointerdown
、 pointerup
和pointermove
。 Pointer events work for both mouse and touch interactions.指针事件适用于鼠标和触摸交互。touch-action: none
to your canvas CSS.将touch-action: none
添加到您的画布 CSS。 This prevents the dragging of your finger from triggering the device's panning action (which stops your drawing).这可以防止您的手指拖动触发设备的平移操作(这会停止您的绘图)。pointerdown
.在pointerdown
设置“鼠标”坐标。 This will stop previous lines from being connected to new ones.这将阻止以前的线路连接到新的线路。 var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var container = document.getElementById('container'); canvas.width = 400; canvas.height = 300; var mouse = {x: 0, y: 0}; canvas.addEventListener('pointermove', function(e) { mouse.x = e.pageX - this.offsetLeft; mouse.y = e.pageY - this.offsetTop; }, false); ctx.lineJoin = 'round'; ctx.lineCap = 'round'; ctx.strokeStyle = 'black'; canvas.addEventListener('pointerdown', function(e) { mouse.x = e.pageX - this.offsetLeft; mouse.y = e.pageY - this.offsetTop; ctx.beginPath(); ctx.moveTo(mouse.x, mouse.y); canvas.addEventListener('pointermove', onPaint, false); }, false); canvas.addEventListener('pointerup', function() { canvas.removeEventListener('pointermove', onPaint, false); }, false); var onPaint = function() { ctx.lineTo(mouse.x, mouse.y); ctx.stroke(); };
#canvas { border: 1px solid rgba(0,0,0,.5); touch-action: none; }
<div id="container"> <canvas id="canvas"></canvas> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.