1. 程式人生 > >canvas 實現滑鼠畫出矩形

canvas 實現滑鼠畫出矩形

 

 

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>Document</title>
<script>
var startX, startY;

var isdown=0
function mouseUp(e,d)
{
	isdown=0;
	var c=document.getElementById("myCanvas");
	height=c.style.height
	width=c.style.width
	var ctx=c.getContext("2d");
	ctx.clearRect(0,0,350,350);
	      
}
function mouseDown(e,d)
{
	down_id=e.id;
	startX = d.pageX;
	startY = d.pageY;
	isdown=1;
	console.log(startX+",,,,"+startY)
}

function mousemove(e){
	if(isdown){
		//console.log(e.pageX+","+e.pageY)
		// 更新 box 尺寸
		//ab.style.width = e.pageX - startX + 'px';
		//ab.style.height = e.pageY - startY + 'px';
		//獲取頁面中的canvas畫布容器,通常為一個div
		var c=document.getElementById("myCanvas");
		height=c.style.height
		width=c.style.width
		var ctx=c.getContext("2d");
		ctx.lineWidth=1;
		ctx.clearRect(0,0,350,350);

		ctx.beginPath();
		ctx.moveTo(startX,startY);
		ctx.lineTo(e.pageX,startY);//shang heng
		ctx.lineTo(e.pageX,e.pageY);//you
		ctx.lineTo(startX,e.pageY);//zuo
		ctx.closePath();
		ctx.stroke();
	}
}
</script>
</head>
<body onmouseup="mouseUp(this,event)" onmousemove="mousemove(event)" onmousedown='mouseDown(this,event)'>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
您的瀏覽器不支援 HTML5 canvas 標籤。</canvas>


</body>
</html>