html5 (canvas) +css+js 实现画图工具

效果图:

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
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值