当另一个函数停止时,停止运行javascript函数?

时间:2014-02-03 18:06:52

标签: javascript canvas

下面的代码是一个完整的绘图应用程序,但是刷子和方块的功能只能使用一次。使用画笔并尝试更改为方形后,它们都会同时运行,因此不会仅绘制正方形,也会同时绘制圆形。我该如何停止这个功能?我已经标记了画笔和方块的代码开始的位置

<!DOCTYPE html>
<html>
<head>
<title>Drawing</title>

<meta charset="UTF-8">
<style type="text/css">
    #toolbar{
        width:983px;
        height:50px;
        padding:10px;
        background:#2f2f2f;
        margin-bottom:1px;
        font-family: sans-serif;
        color:#ffffff;
            user-select: none;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;

    }
    .sizecontrol{
        width:30px;
        height:30px;
        background: #4f4f4f;
        display: inline-block;
        text-align:center;
        padding:5px;
        box-sizing: border-box;
        -moz-box-sizing: border-box;
        user-select: none;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;

    }
    #size{
        float:left;
    }
    #colors{
        float:right;
    }
    .swatch{
        width: 30px;
        height: 30px;
        border-radius:15px;
        box-shadow: inset 0px 1px 0px rgba(255, 255, 255, 0.5), 0px 2px 2px rgba(0, 0, 0, 0.5);
        -webkit-box-shadow: inset 0px 1px 0px rgba(255, 255, 255, 0.5), 0px 2px 2px rgba(0, 0, 0, 0.5);
        display: inline-block;
        margin-left: 10px;
        background-color:cyan;
        box-sizing: border-box;
    }
    .swatch.active{
        border:#fff solid 3px;
        box-shadow:inset 0px 1px 2px rgba(0, 0, 0, 0.5);
        -webkit-box-shadow:inset 0px 1px 2px rgba(0, 0, 0, 0.5);
        box-sizing: border-box;
    }

    .tools{
        float:left;
        height:30px;
        padding: 8px;
        background-color: #434343;
        box-sizing: border-box;
        margin-left:5px;

    }
    .tools:hover{
        background:#818181;
    }

</style>
</head>
<body style="background:#999;" >


    <div id="content">
        <div id="toolbar">
            <div id="size">
                Size <span id="sizeval">10</span>

                <div id="decsize" class="sizecontrol">-</div><!-- Close decsize -->
                <div id="incsize" class="sizecontrol">+</div><!-- Close incsize -->
            </div><!-- Close div size -->
            <div id="colors">
                <div class="swatch" style="background-color:#FF0000"></div>
                <div class="swatch" style="background-color:#00FF00"></div>
                <div class="swatch" style="background-color:#0000FF;"></div>
                <div class="swatch" style="background-color:#FFFF00;"></div>
                <div class="swatch" style="background-color:#00FFFF;"></div>
                <div class="swatch" style="background-color:#FF00FF;"></div>
                <div class="swatch" style="background-color:#FF8000;"></div>
                <div class="swatch" style="background-color:#848484;"></div>
                <div class="swatch" style="background-color:#000;"></div>
                <div class="swatch" style="background-color:#FFF;"></div>
            </div><!-- close colors div -->
            <div id="save" class="tools">Save</div><!-- close save div -->
            <div id="clear" class="tools">Clear</div><!-- close clear div -->
            <div id="square" class="tools" >Square</div><!-- close square div -->
            <div id="brush" class="tools">brush</div><!-- close square div -->
        </div><!-- close div tool bar --> 
        <canvas id="canvas" style="background:#FFFFFF;border: 1px solid #000;">
            Sorry Your Browser is not upto date enough for this app. Plese update your browser
        </canvas>


        <script type="text/javascript" language="javascript">




            var canvas = document.getElementById('canvas');
            var context = canvas.getContext('2d');
            var size = 10;
            var dragging = false;
            var squareEngage = false;
            var brushEngage = false;

            canvas.width = 1000;
            canvas.height = 550;
            context.lineWidth = size*2;





            var setSize = function(newSize){

                function isInt(n) {
                    return n % 1 === 0;
                }
                if(isInt(newSize) == false){
                    newSize = newSize - 0.5;
                }else if(newSize <= 5){
                    interval = 1;
                }else if(newSize <= 22){
                    interval = 2;
                }else if(newSize > 20){
                    interval = 5;
                }
                if(newSize == 22){
                    newSize = 25;
                }

                if(newSize<minSize){
                    newSize = minSize;
                }else if(newSize>maxSize){
                    newSize = maxSize;
                }
                size = newSize;
                context.lineWidth = size*2;

                SizeSpan.innerHTML=size;
            }

            var minSize = 0.5;
            var maxSize = 100;
            var defaultSize = 20;
            var interval = 5;
            var SizeSpan = document.getElementById('sizeval');
            var decSize = document.getElementById('decsize');
            var incSize = document.getElementById('incsize');
            var clear = document.getElementById('clear');
            var square = document.getElementById('square');
            var brush = document.getElementById('brush');   



/////////////////////////// Function for the square to draw \\\\\\\\\\\\\\\\\\\\\\\\\\\\
                square.addEventListener('click', function(){

                squareEngage = true;

                brush.addEventListener('click', function(){
                    squareEngage = false;

                });


            if(squareEngage == true){
                var putPoint2 = function(e){
                    if(dragging2){


                        context.fillRect(e.offsetX, e.offsetY,size,size);

                    }
                }

                var engage2 = function(e){
                    dragging2 = true;
                    putPoint2(e);
                }
                var disengage2 = function(){
                    dragging2 = false;
                    context.beginPath();
                }

                    canvas.addEventListener('mousedown', engage2);
                    canvas.addEventListener('mousemove', putPoint2); //Looks for when the mouse is pressed down
                    canvas.addEventListener('mouseup', disengage2);
                }


            });

/////////////////////////// Function for the brush to draw \\\\\\\\\\\\\\\\\\\\\\\\\\\\
            brush.addEventListener('click', function(){

                square.addEventListener('click', function(){

                    brushEngage = false;
                });
                brushEngage = true;

            if(brushEngage == true){
                var putPoint = function(e){
                if(dragging){
                context.lineTo(e.offsetX, e.offsetY);
                context.stroke();
                context.beginPath(); //This starts the path drawing
                context.arc(e.offsetX, e.offsetY, size, 0, Math.PI*2); //This is the paointer cirlce that will be drawn 
                context.fill();
                context.beginPath();
                context.moveTo(e.offsetX, e.offsetY);

                }
            }

            var engage = function(e){
                dragging = true;
                putPoint(e);

            }
            var disengage = function(){
                dragging = false;
                context.beginPath();
            }

                canvas.addEventListener('mousedown', engage);
                canvas.addEventListener('mousemove', putPoint); //Looks for when the mouse is pressed down
                canvas.addEventListener('mouseup', disengage);
            }


            });

            decSize.addEventListener('click', function(){
                setSize(size-interval);


            });
            clear.addEventListener('click', function(){
                canvas.width = 1000;
                canvas.height = 550;
                context.lineWidth = size*2;
            });
            incSize.addEventListener('click', function(){
                setSize(size+interval);
            });
            setSize(defaultSize);


            var swatches = document.getElementsByClassName('swatch');
                for(var i=0, n=swatches.length;i<n;i++){
                    swatches[i].addEventListener('click', setSwatch);

                }

            for(var i=0,n=colors.length;i<n;i++){
                var swatch = document.createElement('div');
                swatch.className = 'swatch';

            }

                function setColor(color){
                        context.fillStyle = color;
                        context.strokeStyle = color;
                        var active = document.getElementsByClassName('active')[0];
                        if(active){
                            active.className = 'swatch';
                        }
                }
            function setSwatch(e){
                    //Identifiy swatch
                    var swatch = e.target;
                    setColor(swatch.style.backgroundColor);
                    swatch.className += ' active';
                }
            setSwatch({target: document.getElementsByClassName('active')[0]});




        </script>
    </div><!-- Close content -->



</body>
</html>

2 个答案:

答案 0 :(得分:0)

不要嵌套您的事件侦听器。改变

         brush.addEventListener('click', function(){

            square.addEventListener('click', function(){

                brushEngage = false;
            });
            brushEngage = true;

            ...

        brush.addEventListener('click', function(){

            squareEngage = false;
            brushEngage = true;

            ...

        square.addEventListener('click', function(){

            brushEngage = false;
        });

        brush.addEventListener('click', function(){

            brushEngage = true;

            ...

答案 1 :(得分:0)

这是一个快速修复的JS:

window.onload = function () {
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    var size = 10;
    var dragging = false;
    var dragging2 = false; // Added missing declaration
    var engaged; // Added declaration for rescoped function
    var engaged2; // Added declaration for rescoped function
    // Removed extra variables
    canvas.width = 1000;
    canvas.height = 550;
    context.lineWidth = size * 2;
    var setSize = function (newSize) {
        function isInt(n) {
            return n % 1 === 0;
        }
        if (isInt(newSize) == false) {
            newSize = newSize - 0.5;
        } else if (newSize <= 5) {
            interval = 1;
        } else if (newSize <= 22) {
            interval = 2;
        } else if (newSize > 20) {
            interval = 5;
        }
        if (newSize == 22) {
            newSize = 25;
        }
        if (newSize < minSize) {
            newSize = minSize;
        } else if (newSize > maxSize) {
            newSize = maxSize;
        }
        size = newSize;
        context.lineWidth = size * 2;
        SizeSpan.innerHTML = size;
    }
    var minSize = 0.5;
    var maxSize = 100;
    var defaultSize = 20;
    var interval = 5;
    var SizeSpan = document.getElementById('sizeval');
    var decSize = document.getElementById('decsize');
    var incSize = document.getElementById('incsize');
    var clear = document.getElementById('clear');
    var square = document.getElementById('square');
    var brush = document.getElementById('brush');
     // Function for the square to draw
    square.addEventListener('click', function () {
        // Removed extra code
        var putPoint2 = function (e) {
            if (dragging2) {
                context.fillRect(e.offsetX, e.offsetY, size, size);
            }
        };
        engage2 = function (e) { // Made engage2() "global" to refer it in engage()
            dragging2 = true;
            putPoint2(e);
            canvas.addEventListener('mousemove', putPoint2); // Repositioned event attachment
            canvas.addEventListener('mouseup', disengage2); // Repositioned event attachment
        };
        var disengage2 = function () {
            dragging2 = false;
            context.beginPath();
            canvas.removeEventListener('mousemove', putPoint2); // Added event detachment
            canvas.removeEventListener('mouseup', disengage2); // Added event detachment
        };
        if (typeof engage === 'function') { // Added event detachment
            canvas.removeEventListener('mousedown', engage);
        }
        canvas.addEventListener('mousedown', engage2);
    });         
    // Function for the brush to draw
    brush.addEventListener('click', function () {
        // Removed extra code
        var putPoint = function (e) {
                if (dragging) {
                    context.lineTo(e.offsetX, e.offsetY);
                    context.stroke();
                    context.beginPath();
                    context.arc(e.offsetX, e.offsetY, size, 0, Math.PI * 2);
                    context.fill();
                    context.beginPath();
                    context.moveTo(e.offsetX, e.offsetY);
                }
            };
            engage = function (e) { // Made engage() "global" to refer it in engage2()
                dragging = true;
                putPoint(e);
                canvas.addEventListener('mousemove', putPoint); // Repositioned event attachment
                canvas.addEventListener('mouseup', disengage); // Repositioned event attachment
            };
            var disengage = function () {
                dragging = false;
                context.beginPath();
                canvas.removeEventListener('mousemove', putPoint); // Added event detachment
                canvas.removeEventListener('mouseup', disengage); // Added event detachment
            };
            if (typeof engage2 === 'function') { // Added event detachment
                canvas.removeEventListener('mousedown', engage2);
            }
            canvas.addEventListener('mousedown', engage);               
    });
    decSize.addEventListener('click', function () {
        setSize(size - interval);
    });         
    clear.addEventListener('click', function () {
        canvas.width = 1000;
        canvas.height = 550;
        context.lineWidth = size * 2;
    });         
    incSize.addEventListener('click', function () {
        setSize(size + interval);
    });         
    setSize(defaultSize);
    var swatches = document.getElementsByClassName('swatch');
    for (var i = 0, n = swatches.length; i < n; i++) {
        swatches[i].addEventListener('click', setSwatch);
    }
    for (var i = 0, n = colors.length; i < n; i++) {
        var swatch = document.createElement('div');
        swatch.className = 'swatch';
    }
    function setColor(color) {
        context.fillStyle = color;
        context.strokeStyle = color;
        var active = document.getElementsByClassName('active')[0];
        if (active) {
            active.className = 'swatch';
        }
    }
    function setSwatch(e) {
        var swatch = e.target;
        if (swatch) { // Added existense check for swatch
            setColor(swatch.style.backgroundColor);
            swatch.className += ' active';
        }
    }           
    setSwatch({
        target: document.getElementsByClassName('active')[0]
    });
};

正如您所看到的,我已将整个脚本包装在window.onload中以避免全局变量。更改会在它们出现的行上发表评论。

A live demo at jsFiddle。看起来这个代码在FF中不起作用,虽然在Chrome和IE11中它工作正常。使用FF运行时没有错误,但没有绘制任何内容。