使用canvas画布利用js通过鼠标实现矩形的绘制(任意方向的绘制图形)

17 篇文章 0 订阅

使用canvas画布利用js通过鼠标实现矩形的绘制(任意方向的绘制图形)(如果要绘制其他图形,做一点小改动就行了)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        #cav{

            position: absolute;

            border:1px solid black;

        }
    </style>
</head>
<body>
<canvas id='cav' width="500" height="400" style='background-color: #F0F8FF'></canvas>

<script>

    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 = {};

    }

    MyPaint.prototype.paintRect = function(){

        var myPaint = this;

        this.canvas.addEventListener('mousedown',function(e){

            console.info('mousedown',this);

            this.p1.x = e.offsetX;

            this.p1.y = e.offsetY;

            this.canvas.addEventListener("mousemove",myDrect);

            this.canvas.addEventListener("mouseup",function(){

                console.info("mouseup");

                console.info(myDrect);

                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();

</script>
</body>
</html>
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值