杨小杰博客提供免费教程下载和网站搭建技术教程,主要分享和发布网站源码,致力创造一个高质量网络资源教程的分享平台

Canvas画板

Young小杰2017-11-4 18:11网站搭建 (4)2041已收录小标签: pyoblog 网站源码 html源码 canvas

Html5Canvas打造的画图板,利用鼠标点击移动画图,完成之后可以保存为png格式的图片。

canvas画板.png

小杰鼠标画的,见谅,代码如下


<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>canvas画板</title>
</head>

<body>
<div style="width:600px;height:350px;"><canvas style="background-color:#efefef;border:1px solid #ddd;" id="myCanvas"></canvas></div>

		<div style="width:600px;text-align:center;margin-top:30px;">
			<button onclick="clean();">清 空</button>
			<button onclick="save();">生成图片</button>
		</div>

		<img id='img' alt='' />
		
		<script type="text/javascript">
			var canvas,board,img;
			 canvas = document.getElementById('myCanvas');
			 img= document.getElementById('img');
			
			 canvas.height = 350;
			 canvas.width = 600;
			
			 board = canvas.getContext('2d');
			
			 var mousePress = false;
			 var last = null;
			
			 function beginDraw(){
			 mousePress = true;
			}
			
			 function drawing(event){
			event.preventDefault();
			if(!mousePress)return;
			 var xy = pos(event);
			if(last!=null){
			board.beginPath();
			board.moveTo(last.x,last.y);
			board.lineTo(xy.x,xy.y);
			board.stroke();
			}
			 last = xy;
			
			}
			
			 function endDraw(event){
			 mousePress = false;
			 event.preventDefault();
			 last = null;
			}
			
			 function pos(event){
			 var x,y;
			if(isTouch(event)){
			 x = event.touches[0].pageX;
			 y = event.touches[0].pageY;
			}else{
			 x = event.offsetX+event.target.offsetLeft;
			 y = event.offsetY+event.target.offsetTop;
			}
			 return {x:x,y:y};
			}
			
			 function log(msg){
			 var log = document.getElementById('log');
			 var val = log.value;
			 log.value = msg+'n'+val; 
			}
			
			 function isTouch(event){
			 var type = event.type;
			if(type.indexOf('touch')>=0){
			 return true;
			}else{
			 return false;
			}
			}
			
			 function save(){
			 var dataUrl = canvas.toDataURL();
			 img.src = dataUrl;
			}
			
			
			 function clean(){
			board.clearRect(0,0,canvas.width,canvas.height);
			
			}
			
			 board.lineWidth = 1;
			board.strokeStyle="#2AA6C0";
			 canvas.onmousedown = beginDraw;
			 canvas.onmousemove = drawing;
			 canvas.onmouseup = endDraw;
			canvas.addEventListener('touchstart',beginDraw,false);
			canvas.addEventListener('touchmove',drawing,false);
			canvas.addEventListener('touchend',endDraw,false);
		</script>


</body>
</html>
原文地址:pyoblog



评论排行榜

(切勿水评,一经发现封IP)

评论:

1 Google Chrome 55.0.2883.87 Windows 7广西柳州市 电信 2017-11-05 16:58
改成gb2312就好了
Young小杰四川省成都市 移动数据上网公共出口 2017-11-05 17:01
@1:谢谢反馈
1 Google Chrome 55.0.2883.87 Windows 7广西柳州市 电信 2017-11-05 16:57
utf-8是乱码哎。。。改成中文简体就好惹୧(๑•̀⌄•́๑)૭如果我说错了请大佬纠正,我还是个萌新
Young小杰四川省成都市 移动数据上网公共出口 2017-11-05 16:58
@1:没注意这个

发表评论:

签到 赞赏 丢小花 请勾选我再发表评论!