console
function MyPaint(id,color='red'){
var canvas = document.getElementById(id)
this.canvas = canvas;
this.color = color;
this.ctx = this.canvas.getContext('2d');
this.p1= {};
this.p2 = {};
this.p3 = {};
this.rectList = [];
document.querySelector('.draw-img').onload = function () {
canvas.width = this.width
canvas.height = this.height
}
}
MyPaint.prototype.paintRect = function(){
this.canvas.addEventListener('mousedown',function(e){
let myPaint = this
this.p1.x = e.offsetX;
this.p1.y = e.offsetY;
function paint(event){
myDrect.call(myPaint, event)
myPaint.rectList.forEach(v => paintRect.call(myPaint, v.p1, v.p2, true))
}
this.canvas.addEventListener("mousemove",paint);
this.canvas.addEventListener("mouseup",function mouseup(e2){
console.log(e2)
myPaint.rectList.push(JSON.parse(JSON.stringify({p1:myPaint.p1, p2: myPaint.p2})))
myPaint.canvas.removeEventListener("mousemove",paint);
myPaint.canvas.removeEventListener("mouseup",mouseup);
})
}.bind(this));
}
MyPaint.prototype.clear = function () {
this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)
this.rectList = []
}
MyPaint.prototype.clearIndex = function (index) {
debugger
this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)
this.rectList.splice(index, 1)
this.rectList.forEach(v=>paintRect.call(this, v.p1, v.p2, true))
}
function myDrect(e){
this.p2.x = e.offsetX;
this.p2.y = e.offsetY;
this.ctx.width = this.width;
this.ctx.height = this.height;
this.ctx.fillStyle = '#FF0000';
this.ctx.strokeStyle = '#FF0000';
this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);
paintRect.call(this, this.p1, this.p2)
}
function paintRect(p1, p2, flag){
this.ctx.beginPath();
var width = Math.abs(p1.x-p2.x);
var height = Math.abs(p1.y-p2.y);
if(p2.x>=p1.x){
if(p2.y>=p1.y){
this.ctx.rect(p1.x,p1.y,width,height);
}else{
this.ctx.rect(p1.x,p1.y,width,-height);
}
}else{
if(p2.y>=p1.y){
this.ctx.rect(p1.x,p1.y,-width,height);
}else{
this.ctx.rect(p1.x,p1.y,-width,-height);
}
}
this.ctx.stroke();
this.ctx.save();
}
function clearCanvas() {
mp.clear();
}
function clearIndexCanvas(index) {
mp.clearIndex(index)
}
function showEle() {
var html = `<div></div>`
}
var mp = new MyPaint('cav');
mp.paintRect();
<div>
<div class="draw-box">
<canvas id="cav"></canvas>
<img class="draw-img" src="https://pic1.zhimg.com/90/v2-b703e5158ba820157b39337ee211ec5f_250x0.jpg?source=31184dd1" style="background:yellow;width:500px;height:500px" />
</div>
<button onclick="clearCanvas()">clear</button>
<button onclick="clearIndexCanvas(0)">clear0</button>
</div>
.draw-box{
position: relative;
}
#cav{
position: relative;
z-index: 1;
box-sizing: content-box;
}
.draw-img{
display: block;
position: absolute;
z-index: 0;
left: 0;
top: 0;
}