码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2020-04-01 13:03:36      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:其他   har   head   fill   console   通过   div   offsetx   osi   

## 使用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>

  

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

标签:其他   har   head   fill   console   通过   div   offsetx   osi   

原文地址:https://www.cnblogs.com/Liang-Tsai/p/12611607.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!