首页 > 代码库 > 用canvas实现鼠标拖动绘制矩形框
用canvas实现鼠标拖动绘制矩形框
需要用到jCanvas插件和jQuery。
jCanvas下载:https://raw.githubusercontent.com/caleb531/jcanvas/master/jcanvas.min.js
代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>鼠标拖动绘制矩形框(canvas)</title> </head> <body> <canvas id="canvas" width="600" height="300" style="border: 1px solid #000;"></canvas> <script src="./jquery-1.11.3.min.js"></script> <script src="./jcanvas.min.js"></script> <script> var layer=0; CanvasExt = { drawRect:function(canvasId,penColor,strokeWidth){ var that=this; that.penColor=penColor; that.penWidth=strokeWidth; var canvas=document.getElementById(canvasId); //canvas 的矩形框 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(); } } }; drawPen(); function drawPen(){ var color = "red"; var width = 1; CanvasExt.drawRect("canvas",color,width); } </script> </body> </html>
效果大概如下:
用canvas实现鼠标拖动绘制矩形框
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。