在画布中平滑用户绘制的线 [英] Smooth user drawn lines in canvas

查看:90
本文介绍了在画布中平滑用户绘制的线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用< canvas> 以签名的形式捕获用户输入,并试图找出如何平滑鼠标的输入。 / p>

我想我需要通过chunk处理用户的鼠标移动chunk和平滑每个块,我不是在超平滑后,任何改善锯齿状输入将是好的。



感谢,
标记

解决方案

可能会帮助你,
我几分钟后从头开始写这个代码。



试试 http://jsbin.com/ateho3



标记

 code>< canvas id =canvas>< / canvas> 

JavaScript

  window.onload = function(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var width = window.innerWidth;
var height = window.innerHeight;
canvas.height = height;
canvas.width = width;
canvas.addEventListener('mousedown',function(e){
this.down = true;
this.X = e.pageX;
this.Y = e.pageY ;
this.color = rgb();
},0);
canvas.addEventListener('mouseup',function(){
this.down = false;
},0);
canvas.addEventListener('mousemove',function(e){
this.style.cursor ='pointer';
if(this.down){
ctx.beginPath );
ctx.moveTo(this.X,this.Y);
ctx.lineCap ='round';
ctx.lineWidth = 3;
ctx.lineTo(e .pageX,e.pageY);
ctx.strokeStyle = this.color;
ctx.stroke();

this.X = e.pageX;
this.Y = e.pageY;
}
},0);

function rgb(){
color ='rgb(';
for(var i = 0; i <3; i ++){
color + = Math .floor(Math.random()* 255)+',';
}
return color.replace(/ \,$ /,')');
}
};


I'm using <canvas> to capture user input in the form of a signature and am trying to figure out how to smooth the input from the mouse.

I think I need to process the user's mouse movements chunk by chunk and smooth each chunk, I'm not after super smoothing but any improvement on the jagged input would be good.

Thanks, Mark

解决方案

Not sure this might help you, I wrote this code from scratch in few minutes.

Give it a try http://jsbin.com/ateho3

markup :

<canvas id="canvas"></canvas> 

JavaScript :

window.onload = function() {
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    var width  = window.innerWidth;
    var height = window.innerHeight;
    canvas.height = height;
    canvas.width = width;
    canvas.addEventListener('mousedown', function(e) {
      this.down = true;  
      this.X = e.pageX ;
      this.Y = e.pageY ;
      this.color = rgb();
    }, 0);
    canvas.addEventListener('mouseup', function() {
      this.down = false;      
    }, 0);
    canvas.addEventListener('mousemove', function(e) {
      this.style.cursor = 'pointer';
      if(this.down) {
          ctx.beginPath();
          ctx.moveTo(this.X, this.Y);
          ctx.lineCap = 'round';
           ctx.lineWidth = 3;
          ctx.lineTo(e.pageX , e.pageY );
          ctx.strokeStyle = this.color;
          ctx.stroke();

         this.X = e.pageX ;
         this.Y = e.pageY ;
      }
    }, 0);

    function rgb() {
      color = 'rgb(';
      for(var i = 0; i< 3; i++) {
        color += Math.floor(Math.random() * 255)+',';
      }
      return color.replace(/\,$/,')');
    }    
  };

这篇关于在画布中平滑用户绘制的线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆