SOURCE

console 命令行工具 X clear

                    
>
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 = {};
        document.querySelector('.draw-img').onload = function () {
          canvas.width = this.width
          canvas.height = this.height
        }
    }
 
    MyPaint.prototype.paintRect = function(){
        var myPaint = this;
        this.canvas.addEventListener('mousedown',function(e){
            this.p1.x = e.offsetX;
            this.p1.y = e.offsetY;
            this.canvas.addEventListener("mousemove",myDrect);
            this.canvas.addEventListener("mouseup",function(e2){
                this.removeEventListener("mousemove",myDrect);
            })
 
        }.bind(this));
 
        function myDrect(e){
            myPaint.p2.x = e.offsetX;
            myPaint.p2.y = e.offsetY;
            myPaint.ctx.width = myPaint.width;
            myPaint.ctx.height = myPaint.height;
            myPaint.ctx.fillStyle = '#FF0000';
            myPaint.ctx.strokeStyle = '#FF0000';
            var width = Math.abs(myPaint.p1.x-myPaint.p2.x);
            var height = Math.abs(myPaint.p1.y-myPaint.p2.y);
            myPaint.ctx.clearRect(0,0,myPaint.canvas.width,myPaint.canvas.height);
            myPaint.ctx.beginPath();
            if(myPaint.p2.x>=myPaint.p1.x){
                if(myPaint.p2.y>=myPaint.p1.y){
                    myPaint.ctx.rect(myPaint.p1.x,myPaint.p1.y,width,height);
                }else{
                    myPaint.ctx.rect(myPaint.p1.x,myPaint.p1.y,width,-height);
                }
            }else{
                if(myPaint.p2.y>=myPaint.p1.y){
                    myPaint.ctx.rect(myPaint.p1.x,myPaint.p1.y,-width,height);
                }else{
                    myPaint.ctx.rect(myPaint.p1.x,myPaint.p1.y,-width,-height);
                }
 
            }
            myPaint.ctx.stroke();
            myPaint.ctx.save();
        }
    }
 
    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>
</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;
        }