<!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>