用HTML5 Canvas做一個畫圖板


<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>用HTML5 Canvas做一個畫圖板</title>
<style type="text/css">
		body,p{margin:0;padding:0;}
		.content {
			display: block;
			font-size: 14px;
			margin: 0px 2px 0px 2px;
			padding: 0px 15px 0px 15px;
			line-height: 150%;
			color: #1A2536;
			font-family: "PT Serif", Georgia, Times, "Times New Roman", "Heiti SC", "Microsoft Yahei", "微軟雅黑", "宋體", serif;
		}
</style>

</head>
<body>
	<div id="content">
	  <canvas id="the_stage" width="520" height="350" style="border: 1px solid #999;">
	  </canvas>
	</div>  
	
	<script type="text/javascript">
	function Draw(arg){
		if(arg.nodeType){    //判斷結點類型
			this.canvas = arg;		
		}else if(typeof arg =='string'){
			this.canvas = document.getElementById(arg);
		}else{
			return;
		}
		this.init();
	}
	
	Draw.prototype = {
		init:function(){
				var that = this;
				if (!this.canvas.getContext) {   //判斷是否支持Canvas
					return;
				}
				this.context = this.canvas.getContext('2d');
				this.canvas.onselectstart = function(){  //去掉選擇
					return false;
				};
				this.canvas.onmousedown = function(){
					that.drawBegin(event);
				};
		},
		drawBegin:function(e){
			var that = this,
				 stage_info = this.canvas.getBoundingClientRect();   //getBoundingClientRect()可以不用考慮兼容性
			window.getSelection()?window.getSelection().removeAllRanges():document.selection.empty(); //清除文本的選中
			
			this.context.moveTo(
				e.clientX - stage_info.left,
				e.clientY - stage_info.top			
			);
			document.onmousemove = function(){
				that.drawing(event);
			};
			document.onmouseup = this.drawEnd;		 
		},
		drawing:function(e){
			var stage_info = this.canvas.getBoundingClientRect();
			
			this.context.lineTo(
				e.clientX - stage_info.left,
				e.clientY - stage_info.top			
			);
			this.context.stroke();   //相當與fill(),填充
		},
		
		drawEnd:function(){
			document.onmousemove = document.onmouseup = null;		//釋放內存
		}
		
	};
	
	var draw = new Draw('the_stage');

</script>
</body>
</html>

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM