欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

canvas实现简单的画图工具中画笔效果,外加画好的笑脸

程序员文章站 2022-06-24 19:43:05
...
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>canvas实现简单的画图工具中画笔效果,外加画好的笑脸</title>
</head>
<body>
	<canvas width="500" height="500" style="background:#eee;"></canvas>
	<script>
		var canvas = document.getElementsByTagName('canvas')[0];
		var con = canvas.getContext('2d');
		canvas.onmousedown = function(e){
			var mx = e.layerX,
				my = e.layerY;
				con.moveTo(mx,my);
			canvas.onmousemove = function(e){
				var ex = e.layerX,
					ey = e.layerY;
				con.lineTo(ex,ey);
				con.stroke();
			}
			canvas.onmouseup = function(){
				canvas.onmousemove = null;
				canvas.onmouseup = null;
			}
		}
		//绘制矩形
		function myDrawRect(x,y,w,h){
			//从新开辟路径
			con.beginPath();
			con.moveTo(x,y);
			con.lineTo(x+w,y);
			con.lineTo(x+w,y+h);
			con.lineTo(x,y+h);
			//加上 closePath 会自动闭合路径
			con.closePath();
			con.stroke();
		}
		myDrawRect(200,200,30,40);
		myDrawRect(275,200,30,40);
		//绘制圆形
		function myDrawCircle(x,y,r){
			con.beginPath();
			for(var i=0;i<360;i++){
				con.lineTo(x+r*Math.cos(i*Math.PI/180),y+r*Math.sin(i*Math.PI/180));
				con.stroke();
			}
			con.closePath();
		}
		myDrawCircle(250,250,100);
		//半圆
		function myDrawCircle1(x,y,r){
			con.beginPath();
			for(var i=0;i<180;i++){
				con.lineTo(x+r*Math.cos(i*Math.PI/180),y+r*Math.sin(i*Math.PI/180));
				con.stroke();
			}
			//最后加上一条半径长度的直线。
			con.lineTo(x+r,y);
			con.stroke();
			con.closePath();
		}
		myDrawCircle1(250,260,70);
	</script>
</body>
</html>