效果图:
js:
var canvas= document.getElementById("cans");
var cxt=canvas.getContext("2d");
var startX,startY,endX,endY;
var data;
var shapes = new Array();
var mousedown,mouseout;
var shape=1;
// 创建图形对象,保存该图形的开始、结束坐标以及相关属性
function create_shape(Shape,startx,starty,endx,endy){
var color = cxt.strokeStyle.toString();
var size = cxt.lineWidth;
shapes[shapes.length]={
"Shape":Shape,
"startx":startx,
"endx":endx,
"starty":starty,
"endy":endy,
"color":color,
"size":size,
"x":[],
"y":[],
};
}
//点击画布,获取起始坐标,由于加了标题栏,坐标存在一个偏移量
function StartPos(e){
mousedown =0;
mouseout = 0;
var rect = canvas.getBoundingClientRect();
startX=e.clientX - rect.left * (canvas.width / rect.width);
startY=e.clientY - rect.top * (canvas.height / rect.height) ;
//如果是任意线,创建该对象
if(shape==4){
create_shape(4,startX,startY,endX,endY);
shapes[shapes.length-1].x.push(startX);
shapes[shapes.length-1].y.push(startY);
}
//如果是橡皮擦,调用擦除功能函数
if(shape==5){
delete_picture();
}
//保存当前画面
data=cxt.getImageData(0, 0, canvas.width, canvas.height);
}
// 获取终点坐标
function EndPos(e){
if(startX!=null){
var rect = canvas.getBoundingClientRect();
endX=e.clientX - rect.left * (canvas.width / rect.width);
endY=e.clientY - rect.top * (canvas.height / rect.height) ;
}
}
// 松开鼠标
function Mouseup(){
if(startX!=null&&endX!=null&&shape!=5&&shape!=4&&!(mousedown==1&&mouseout==1)){
//创建该图形对象,并保存相关属性
create_shape(shape,startX,startY,endX,endY);
endX=null;
}
startX=null;
}
// 按下鼠标
function Mousedown(){
//如果鼠标是在画布外按下的,mousedown=1
if(mouseout == 1)
mousedown=1;
}
// 鼠标移出了画布,mouseout=1
function MouseOut(){
mouseout=1;
}
// 选择画直线
function line(){
shape=1;
}
// 选择画圆
function circle(){
shape=2
}
// 选择画矩形
function rectangle(){
shape=3;
}
// 选择画自由线
function pencil(){
shape=4;
}
// 选择橡皮擦
function rubber(){
shape = 5;
}
// 鼠标移动过程中画画
fun