Dzwebs.Net

撰写电脑技术杂文十余年

canvas实现在线手写绘制画图

Admin | 2016-8-5 16:38:03 | 被阅次数 | 5799

温馨提示!

如果未能解决您的问题,请点击搜索;登陆可复制文章,点击登陆

  一、网页控件

  <canvas width="800" height="600"></canvas>

  二、JS代码

  <script>  
 var canvas = document.getElementsByTagName('canvas')[0];  
 canvas.addEventListener('mousemove', onMouseMove, false);  
 canvas.addEventListener('mousedown', onMouseDown, false);  
 canvas.addEventListener('mouseup', onMouseUp, false);  
 
 var context = canvas.getContext('2d');  
 var linex = new Array();  
 var liney = new Array();  
 var linen = new Array();  
 
 var lastX = -1;  
 var lastY = -1;  
 var hue = 0;  
 var flag = 0;  
 
 function onMouseMove(evt) {  
    if (flag == 1) {  
       linex.push(evt.layerX);  
       liney.push(evt.layerY);  
       linen.push(1);  
       context.save();  
       context.translate(context.canvas.width/2, context.canvas.height/2);  
       context.translate(-context.canvas.width/2, -context.canvas.height/2);  
       context.beginPath();  
       context.lineWidth = 5 + Math.random() * 10;  
 
       for (var i=1;i<linex.length;i++) {  
             lastX = linex[i];  
             lastY = liney[i];  
             if (linen[i] == 0) {  
                context.moveTo(lastX,lastY);  
             } else {  
                context.lineTo(lastX,lastY);  
             }  
       }  
 
       hue = hue + 10 * Math.random();  
       context.strokeStyle = 'hsl(' + hue + ', 50%, 50%)';  
       context.shadowColor = 'white';  
       context.shadowBlur = 10;  
       context.stroke();  
       context.restore();  
    }  
 }  
 function onMouseDown(evt) {  
    flag = 1;  
    linex.push(evt.layerX);  
    liney.push(evt.layerY);  
    linen.push(0);  
 }  
 function onMouseUp(evt) {  
    flag = 0;  
     linex.push(evt.layerX);  
     liney.push(evt.layerY);  
    linen.push(0);  
 }  
</script>


该杂文来自: 网页制作杂文

上一篇:jquery html5 读取本地文件示例代码

下一篇:jquery鼠标经过图片变暗变灰

网站备案号:

网站备案号:滇ICP备11001339号-7

版权属性:

Copyright 2007-2021-forever Inc. all Rights Reserved.

联系方式:

Email:dzwebs@126.com QQ:83539231 访问统计