您的位置:首页 > Web前端 > HTML5

HTML5 Canvas实现web画图之自由绘制矩形

2015-08-02 22:58 686 查看
        接上一篇的自由画笔的绘制,接下来要做的功能是像windows附件中选择矩形框之后,可以在画布上自由绘制矩形。该功能和自由画笔类似,不断的拖动时不断的由当前点和最初的点画一个矩形即可,只不过此时还要删除上一次绘制的矩形,多了一个图层的设置比较的麻烦。

其中JCanvas的API对图层(Layer)的定义:

Each layer can contain only one drawing (rectangle, arc, image, etc.). This is because each drawing is the layer object itself.

也就是说,每个图层只能包含一个画图对象(矩形、扇形、图片等等),,那么在鼠标移动画矩形的时候,就要先删除图层中上一次拖动的而画出的

矩形,然后再画出当前拖动产生的矩形,这样就在不断的拖动的过程中,画布上只画出了一个矩形。所以,自由绘制矩形的过程应该如下:

鼠标按下事件:onmousedown,记录矩形左上角的坐标,画图即将开始,并设置图层名字;
鼠标拖动事件:onmousemove,先根据图层名字,删除该图层。再根据当前点的位置,画一个一个新的矩形;
鼠标左键松开事件:onmousedown,画图结束。

其中涉及的图层操作的方法涉及的参数:

1、addLayer:

type:图层类型,例如:rectangle,矩形图层;ellipse,椭圆图层,等等;
strokeStyle:图层中线条的颜色,为RGB数值;
strokeWidth:图层中线条的宽度;
name:图层名称;
x:图层坐标X;
y:图层坐标Y;
fromCenter: boolean类型,true的时候,表示上面的x,y坐标表示的是中心位置;false的时候,表示的是左上角的位置;
width:图层宽度;
height :图层高度;

其中主要要注意的是fromCenter参数的理解,以画圆的图层为例,true的时候,x,y表示的是圆心的位置,而为false的时候,表示的是圆左上角的位置。

2、removeLayer:

参数只有一个,为Layer名或者Index,根据图层名或者索引移除图层;

接下来就主要是代码部分了,前台部分简单,和上一篇的类似,就不贴出来了,主要贴画图的主要部分代码:

drawRect:function(canvasId,penColor,strokeWidth){
var that=this;
that.penColor=penColor;
that.penWidth=strokeWidth;

var canvas=document.getElementById(canvasId);
var canvasRect = canvas.getBoundingClientRect();
var canvasLeft=canvasRect.left;
var canvasTop=canvasRect.top;

var layerIndex=layer;
var layerName="layer";
var x=0;
var y=0;

canvas.onmousedown=function(e){
var color=that.penColor;
var penWidth=that.penWidth;

layerIndex++;
layer++;
layerName+=layerIndex;
x=e.clientX-canvasLeft;
y=e.clientY-canvasTop;

$("#"+canvasId).addLayer({
type: 'rectangle',
strokeStyle: color,
strokeWidth: penWidth,
name:layerName,
fromCenter: false,
x: x, y: y,
width: 1,
height: 1
});

$("#"+canvasId).drawLayers();
$("#"+canvasId).saveCanvas();
canvas.onmousemove=function(e){
width=e.clientX-canvasLeft-x;
height=e.clientY-canvasTop-y;

$("#"+canvasId).removeLayer(layerName);

$("#"+canvasId).addLayer({
type: 'rectangle',
strokeStyle: color,
strokeWidth: penWidth,
name:layerName,
fromCenter: false,
x: x, y: y,
width: width,
height: height
});

$("#"+canvasId).drawLayers();
}
}

canvas.onmouseup=function(e){
var color=that.penColor;
var penWidth=that.penWidth;

canvas.onmousemove=null;

width=e.clientX-canvasLeft-x;
height=e.clientY-canvasTop-y;

$("#"+canvasId).removeLayer(layerName);

$("#"+canvasId).addLayer({
type: 'rectangle',
strokeStyle: color,
strokeWidth: penWidth,
name:layerName,
fromCenter: false,
x: x, y: y,
width: width,
height: height
});

$("#"+canvasId).drawLayers();
$("#"+canvasId).saveCanvas();
}
}

实现了自由绘制矩形的功能,其他图形,例如圆、正方形、椭圆、箭头等等的啊,就和这类似,比较的简单了,以下是画矩形和椭圆的运行效果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  canvas html5 js