1.效果图
![](https://img-blog.csdnimg.cn/02e9d79b0ff649cbaef7aa18894f20db.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAa29iZWt1bjI0,size_20,color_FFFFFF,t_70,g_se,x_16)
2.html代码
<canvas id='cav' width="600" height="400" style='background-color: #eee'></canvas>
3.js代码
var paint;
var canvas;
var positionList = [];
function MyPaint(id, color = 'red') {
canvas = document.getElementById(id);
this.canvas = canvas;
this.color = color;
this.ctx = this.canvas.getContext('2d');
this.initP = {};
this.endP = {};
}
MyPaint.prototype.paintSelect = function() {
var myPaint = this;
this.canvas.addEventListener('mousedown', function(e) {
this.initP.x = e.offsetX;
this.initP.y = e.offsetY;
this.canvas.addEventListener("mousemove", myDrect);
this.canvas.removeEventListener("mouseup", operate);
this.canvas.addEventListener("mouseup", operate);
}.bind(this));
function operate() {
var initP = JSON.parse(JSON.stringify(myPaint.initP))
var endP = JSON.parse(JSON.stringify(myPaint.endP))
positionList.push({
initP,
endP
})
this.removeEventListener("mousemove", myDrect);
}
function drawPositionList(initP,endP){
var width = Math.abs(initP.x - endP.x);
var height = Math.abs(initP.y - endP.y);
myPaint.ctx.beginPath();
if (endP.x >= initP.x) {
if (endP.y >= initP.y) {
myPaint.ctx.rect(initP.x, initP.y, width, height);
} else {
myPaint.ctx.rect(initP.x, initP.y, width, -height);
}
} else {
if (endP.y >= initP.y) {
myPaint.ctx.rect(initP.x, initP.y, -width, height);
} else {
myPaint.ctx.rect(initP.x, initP.y, -width, -height);
}
}
myPaint.ctx.stroke();
}
function myDrect(e) {
myPaint.endP.x = e.offsetX;
myPaint.endP.y = e.offsetY;
myPaint.ctx.width = myPaint.width;
myPaint.ctx.height = myPaint.height;
myPaint.ctx.fillStyle = '#FF0000';
myPaint.ctx.strokeStyle = '#FF0000';
myPaint.ctx.lineWidth = 4;
var width = Math.abs(myPaint.initP.x - myPaint.endP.x);
var height = Math.abs(myPaint.initP.y - myPaint.endP.y);
myPaint.ctx.clearRect(0, 0, myPaint.canvas.width, myPaint.canvas.height);
if(positionList.length>0){
positionList.forEach(item=>{
drawPositionList(item.initP,item.endP)
})
}
myPaint.ctx.beginPath();
if (myPaint.endP.x >= myPaint.initP.x) {
if (myPaint.endP.y >= myPaint.initP.y) {
myPaint.ctx.rect(myPaint.initP.x, myPaint.initP.y, width, height);
} else {
myPaint.ctx.rect(myPaint.initP.x, myPaint.initP.y, width, -height);
}
} else {
if (myPaint.endP.y >= myPaint.initP.y) {
myPaint.ctx.rect(myPaint.initP.x, myPaint.initP.y, -width, height);
} else {
myPaint.ctx.rect(myPaint.initP.x, myPaint.initP.y, -width, -height);
}
}
myPaint.ctx.stroke();
myPaint.ctx.save();
}
}
paint= new MyPaint('cav');
paint.paintSelect();