将javascript代码实现到其他javascript canvas元素中

时间:2014-02-11 09:13:30

标签: javascript canvas

我已经制作了一个绘图应用程序,但是我不知道如何将两者合并在一起。我需要获取只是在绘图应用程序中绘制线条的代码,但是我正在努力处理所有变量,请帮助一些人

//这是线条图代码,

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    #wrapper{
        position:relative;
        width:300px;
        height:200px;
    }
    #canvas,#canvasTemp{
        position:absolute; top:0px; left:0px;
        border:1px solid blue;
        width:100%;
        height:100%;
    }
    #canvasTemp{ border:1.5px solid green; }
    #canvas{ border:1px solid red; }
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var canvasTemp=document.getElementById("canvasTemp");
    var ctxTemp=canvasTemp.getContext("2d");
    var canvasOffset=$("#canvas").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;

    var startX;
    var startY;
    var isDown=false;

    $("#canvasTemp").css({ left:-500, top:0 });

    function drawLine(toX,toY,context){
        context.beginPath();
        context.moveTo(startX, startY);
        context.lineTo(toX,toY);
        context.stroke();
    }

    function handleMouseDown(e){
      e.preventDefault();
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);

      // save drag-startXY, 
      // move temp canvas over main canvas,
      // set dragging flag
      startX=mouseX;
      startY=mouseY;
      ctxTemp.clearRect(0,0,canvasTemp.width,canvasTemp.height);
      $("#canvasTemp").css({ left:0, top:0 });
      isDown=true;
    }

    function handleMouseUp(e){
      e.preventDefault();
      if(!isDown){return;}
      // clear dragging flag
      // move temp canvas offscreen
      // draw the user's line on the main canvas
      isDown=false;
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      $("#canvasTemp").css({ left:-500, top:0 });
      drawLine(mouseX,mouseY,ctx);
    }

    function handleMouseMove(e){
      e.preventDefault();        
      if(!isDown){return;}
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      // clear the temp canvas
      // on temp canvas draw a line from drag-start to mouseXY
      ctxTemp.clearRect(0,0,canvasTemp.width,canvasTemp.height);
      drawLine(mouseX,mouseY,ctxTemp);
    }

    $("#canvas").mousedown(function(e){handleMouseDown(e);});
    $("#canvas").mousemove(function(e){handleMouseMove(e);});
    $("#canvas").mouseup(function(e){handleMouseUp(e);});
    $("#canvas").mouseout(function(e){handleMouseUp(e);});

}); // end $(function(){});
</script>

</head>

<body>
    <div id="wrapper">
        <canvas id="canvasTemp" width=300 height=200></canvas>
        <canvas id="canvas" width=300 height=200></canvas>
    </div>
</body>
</html>

这是原始绘图应用程序代码

<!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;

    }
    #toolbar > img{


    margin-left:5px;


    }
    .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:3px;
        margin-right:3px;

    }
    .tools:hover{
        background:#818181;
    }
    .newtools{
    float:left;

        padding: 2px;

        box-sizing: border-box;
        margin-left:3px;
        margin-right:3px;
    }

</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:#970000;"></div>
                <div class="swatch" style="background-color:#FF7A00;"></div>
                <div class="swatch" style="background-color:#00FFFF;"></div>
                <div class="swatch" style="background-color:#FFFF00;"></div>
                <div class="swatch" style="background-color:#FF00FF;"></div>
                <div class="swatch" style="background-color:#0000FF;"></div>
                <div class="swatch" style="background-color:#A700C7;;"></div>
                <div class="swatch" style="background-color:#02850C;"></div>
                <div class="swatch" style="background-color:#00FF00"></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="rubber" class="tools">Rubber</div><!-- close clear div -->
            <div id="square" class="tools" >Square</div><!-- close square div -->
            <div id="brush" class="tools">Brush</div><!-- close brush 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">


        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');
    var rubber = document.getElementById('rubber');
    var color2 = '#000';

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


        context.fillStyle = '#ffffff';
        context.strokeStyle = '#ffffff';


     });

     // Function for the square to draw
    square.addEventListener('click', function () {
        // Removed extra code
     context.fillStyle = color2;
        context.strokeStyle = color2;
        var putPoint2 = function (e) {
            if (dragging2) {
            var new_size = size/2;
                context.fillRect(e.offsetX-new_size, e.offsetY-new_size, 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 () {
      context.fillStyle = color2;
        context.strokeStyle = color2;
        // 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', engage); // 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) {
    color2 = 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]
    });
};
        </script>
    </div><!-- Close content -->



</body>
</html>

0 个答案:

没有答案