javascript - Canvas Html5 Drawing App,移动 Canvas 导致大问题

标签 javascript css html canvas

我正在创建一个 Html5 绘图应用程序,我已经弄清楚了所有功能,但我现在遇到了问题,因为我现在正处于设计阶段并试图使它看起来不错。我想将我的绘图板居中,但是一旦我将 css 实现到 div 容器,容器就会移动,但它会将绘图板/ Canvas 推出容器,并且它会离开页面远离我的绘图光标。有没有办法让一切都一起正确地移动?谢谢...我提前道歉有相当多的代码

<div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var TestModul = {

    initImage: function(imgSrc) {

        canvas.width = canvas.width;
        if(shapes != null || shapes != undefined){
            shapes = [];
        }

        image.src = imgSrc;
        image.onload = function(){
            context.drawImage(image, 0, 0, canvas.width, canvas.height);
            paintBoard();
        }
    }
};




/*
    Main Part
*/
var canvas;
var context;
var canvas2;
var context2;
var lineWidth;
var radius = 10; 

var shape;
var shapes;
var painting;

var eraser;

var color = "#000000";

var image = new Image();

var SHAPE_TYPE = function(){};
SHAPE_TYPE.CIRCLE = "circle";
SHAPE_TYPE.RECTANGLE = "rectangle";
SHAPE_TYPE.LINE = "line";
SHAPE_TYPE.ERASER = "eraser";
SHAPE_TYPE.TRIANGLE = "triangle";
SHAPE_TYPE.FILL = "fill";


//Variables needed

var movePosition;
var startPosition;
var endPosition;
var object;

function init(){
    canvas = document.getElementById('board');
    context = canvas.getContext('2d');

    canvas2 = document.getElementById('board2');
    context2 = canvas2.getContext('2d');

    
    $('.tools a div').each(function() {
        $(this).click(function () {
            setCursor($(this).attr('id'));
        });
    });


    shape = SHAPE_TYPE.LINE;
    shapes = [];
    painting = false;

    eraser = new Eraser;

    canvas2.onmousedown = onMouseDown;
    canvas2.onmouseup = onMouseUp;
    canvas2.onmousemove = onMouseMove;
    
    canvas.addEventListener("onmousemove", onMouseMove, false);
       canvas2.addEventListener("onmousemove", onMouseMove, false);
}


/*function reOffset(){
  var BB=canvas.getBoundingClientRect();
  offsetX=BB.left;
  offsetY=BB.top;        
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }


var isDown=false;
var startX,startY,mouseX,mouseY;*/





function onMouseDown(event){
    console.log("init.js: onMouseDown()");

    startPosition = new Point(event.pageX - 3*this.offsetLeft - 20, event.pageY - this.offsetTop);
    painting = true;

    color = $('select[name="colorpicker-picker-longlist"]').val();

    if(shape === SHAPE_TYPE.LINE){
        object = new Line(event.pageX - 3*this.offsetLeft - 20, event.pageY - this.offsetTop,color,lineWidth);
    }else if(shape === SHAPE_TYPE.RECTANGLE){
        object = new Rectangle(startPosition.x,startPosition.y,0,0,color,3);
      }else if(shape === SHAPE_TYPE.TRIANGLE){
        object = new Triangle(startPosition.x,startPosition.y,0,0,color,3);
    }else if(shape === SHAPE_TYPE.CIRCLE){
        object = new Circle(startPosition.x,startPosition.y,0,color,3);
    }else if(shape === SHAPE_TYPE.FILL){
        object = new Fill(event.pageX - 3*this.offsetLeft - 20, event.pageY - this.offsetTop,color);
    }

}

function onMouseMove(event){

    movePosition = new Point(event.pageX - 3*this.offsetLeft - 20, event.pageY - this.offsetTop);

    if(shape === SHAPE_TYPE.LINE && painting){
        object.addPoint(event.pageX - 3*this.offsetLeft - 20, event.pageY - this.offsetTop);
    }else if(shape === SHAPE_TYPE.RECTANGLE && painting){
        var x = startPosition.x;
        var y = startPosition.y;
        if (x > movePosition.x) x = movePosition.x;
        if (y > movePosition.y) y = movePosition.y;
        var width = Math.abs(startPosition.x - movePosition.x);
        var height = Math.abs(startPosition.y - movePosition.y);
        object.setPosition(x,y);
        object.width = width; object.height = height;
    }else if(shape === SHAPE_TYPE.CIRCLE && painting){
        var x = startPosition.x;
        var y = startPosition.y;
        if (x > movePosition.x) x = movePosition.x;
        if (y > movePosition.y) y = movePosition.y;
        x += object.radius;
        y += object.radius;
        var d = (movePosition.x - startPosition.x) * (movePosition.x - startPosition.x) +
            (movePosition.y - startPosition.y) * (movePosition.y - startPosition.y);
        var radius = Math.sqrt(d)/2;
        object.setPosition(x,y);
        object.radius = radius;
    }else if(shape === SHAPE_TYPE.ERASER){
      
        eraser.width = $('#brushSize').val();
        eraser.height = $('#brushSize').val();
        eraser.setPosition(movePosition.x - eraser.width/2,movePosition.y - eraser.height/2);
        if(painting){
            shapes.push(new Eraser(eraser.point.x,eraser.point.y,eraser.width,eraser.height));
        }
    }

    if(painting){
        paintBoard();
    }
    paintBoard2();

}

function onMouseUp(event){

    endPosition = new Point(event.pageX - 3*this.offsetLeft - 20, event.pageY - this.offsetTop);
    if(shape === SHAPE_TYPE.LINE && painting){
        object.addPoint(endPosition.x, endPosition.y);
        shapes.push(object);
    }else if(shape === SHAPE_TYPE.RECTANGLE && painting){
        shapes.push(object);
    }else if(shape === SHAPE_TYPE.CIRCLE && painting){
        shapes.push(object);
    }else if(shape === SHAPE_TYPE.ERASER && painting){
        eraser.width = lineWidth;
        eraser.height = lineWidth;
        shapes.push(new Eraser(endPosition.x - eraser.width/2,endPosition.y - eraser.height/2,eraser.width,eraser.height));
    } else if(shape === SHAPE_TYPE.FILL && painting){
        shapes.push(object);
    }

    painting = false;
    object = undefined;

    paintBoard();
}





function paintBoard(){
    console.log("init.js: paintBoard(): shapes.length: " + shapes.length);

    for(var i=0;i<shapes.length;i++){
        shapes[i].draw(context);
    }
}


function paintBoard2(){

    canvas2.width = canvas2.width;

    if(object != undefined && object != null && shape !== SHAPE_TYPE.ERASER){
        object.drawContour(context2);
    }

    if(shape === SHAPE_TYPE.ERASER){
        eraser.drawContour(context2);
    }

}

function reloadBoard(){

    canvas.width = canvas.width;
    context.globalCompositeOperation = "source-over";
    if(image.src.length){
        image.src = image.src + "?" + new Date().getTime();
    }else{
        paintBoard();
    }
}

function undoBoard(){

    if(shapes.length > 0){
        shapes.pop();
        reloadBoard();
    }
}
 




// All JavaScript files loaded

function require_files_loaded () {

    console.log("init.js: require_files_loaded()");
 


//Clear Function

                         
    function clear_canvas_rectangle (){
           if (confirm("are you sure you want to clear your canvas?")) 

        {
    console.log("init.js: clear_canvas_rectangle()");
    context.clearRect (0, 0, 645, 495);
    
    // Clear all current shapes from shape array so they are no longer being drawn.
    shapes = [];

     } else {
        }
        }





/*---------------------------Cursor Stuff--------------------------------*/

function setCursor(id) {
    console.log("init.js: setCursor(): id: " + id);
    
    switch (id) {
        case 'brush':
            shape = SHAPE_TYPE.LINE;
        break;
        case 'circle':
            shape = SHAPE_TYPE.CIRCLE;
        break;
        case 'rectangle':
            shape = SHAPE_TYPE.RECTANGLE;
        break;
        case 'eraser':
            shape = SHAPE_TYPE.ERASER;
        break;
       
       
       
    }
    
    console.log("image path: " + 'cursor_' + id + '.png');
    
  $('.canvas-boards').css('cursor', 'url(../assets/imgs/tools/cursor_' + id + '.png)0 130, auto');
    

   // $('.canvas-boards').css('cursor', 'url(../assets/imgs/tools/brush.png) 0 0, auto');
}

function setLine(){
    console.log('init.js: setLine(): brush');
    shape = SHAPE_TYPE.LINE;
    $('.canvas-boards').css('cursor', 'url(../assets/imgs/tools/cursor_brush.png)0 130, auto');
}
function setCircle(){
    console.log('init.js: setCircle(): circle');
    shape = SHAPE_TYPE.CIRCLE;
    $('.canvas-boards').css('cursor', 'url(../assets/imgs/tools/cursor_circle.png) 0 130, auto');
}
function setRectangle(){
    console.log('init.js: setRectangle(): rect');
    shape = SHAPE_TYPE.RECTANGLE;
    $('.canvas-boards').css('cursor', 'url(../assets/imgs/tools/cursor_rectangle.png) 0 130, auto');
    
    
  
}
function setEraser(){
  
    shape = SHAPE_TYPE.ERASER;
    $('.canvas-boards').css('cursor', 'url(../assets/imgs/tools/eraser.png) 0 130, auto');
}
function setFill(){
    shape = SHAPE_TYPE.FILL;
    $('.canvas-boards').css('cursor', 'url(../assets/imgs/tools/bucket.png) 30 120, auto');
}
      var app = "app";



 Array.prototype.last = function(){
            return this[this.length-1];
        };

        /*
         Point class
         */
        var Point = function(x, y){
            this.x = x;
            this.y = y;
        };



  
        /*
         Shape class (super class of all the shapes)
        */
                var Shape = function( point, color, lineWidth){
                    this.point = point;
                    this.color = color;
                    this.lineWidth = $('#brushSize').val();
                };

                Shape.prototype.draw = function(){
                    console.log("draw");
                };

                Shape.prototype.drawContour = function(){
                    console.log("drawContour");
                };

                Shape.prototype.getPosition = function(){
                    return this.point;
                };

                Shape.prototype.setPosition = function(x,y){
                    this.point = new Point(x,y);
                };

                Shape.prototype.getColor = function(){
                    return this.color;
                };



        /*
         Eraser class
        */
        var Eraser = function(x, y, width, height){
           
                console.log("I WORK");
            this.point = new Point(x,y);
            this.width = $('#brushSize').val();
            this.height = $('#brushSize').val();
            this.color = "white";
            this.contour = "white";
        };

        Eraser.prototype.setPosition = function(x ,y){
            this.point = new Point(x,y);
        };

        Eraser.prototype.draw = function(context){
            context.fillStyle = this.color;
            context.beginPath();
            context.fillRect(this.point.x,this.point.y,this.width,this.height);
            context.closePath();
        };
        Eraser.prototype.drawContour = function(context){
            context.strokeStyle = this.contour;
            context.beginPath();
            context.strokeRect(this.point.x,this.point.y,this.width,this.height);
            context.closePath();
        };

        /*
         Circle class (subclass of Shape class)
         */
        var Circle = function(x, y, radius, color, lineWidth){
            Shape.call(this,new Point(x,y),color, lineWidth);
            this.radius = lineWidth;
        };
        Circle.prototype = Object.create(Shape.prototype);
        Circle.prototype.constructor = Circle;
        Circle.prototype.draw = function(context){
            context.lineWidth = this.lineWidth;
            context.beginPath();
            context.fillStyle = this.color;
            context.arc(this.point.x, this.point.y, this.radius, 0, 2*Math.PI);
            context.fill();
            context.closePath();
        };
        Circle.prototype.drawContour = function(context){
            context.strokeStyle = this.color;
            context.lineWidth = this.lineWidth;
            context.beginPath();
            context.arc(this.point.x, this.point.y, this.radius, 0, 2*Math.PI);
            context.stroke();
            context.closePath();
        };



            /*
             Fill class (subclass of Shape class)
             */
            var Fill = function(x, y, color){
                Shape.call(this,new Point(x,y),color);
            };
            Fill.prototype = Object.create(Shape.prototype);
            Fill.prototype.constructor = Fill;
            Fill.prototype.draw = function(context){
                console.log("app.js: Fill.prototype.draw(): ", context);
                window.ctx = context;

                var imgData = context.getImageData(0,0,context.canvas.width,context.canvas.height);
                var pixelsData = imgData.data;

                var startRGBArray = this.getClickedColor(pixelsData,this.point.x,this.point.y);
                var pickedColorRGBAArray = this.convertHex(this.color,0);

               // console.log(startRGBArray,"clicked");
               // console.log(pickedColorRGBAArray,"picked");

                if(startRGBArray[0] != pickedColorRGBAArray[0] || startRGBArray[1] != pickedColorRGBAArray[1] || startRGBArray[2] != pickedColorRGBAArray[2]){
                    this.fill(this.point.x,this.point.y,startRGBArray[0],startRGBArray[1],startRGBArray[2],startRGBArray[3],context,pixelsData);
                    context.putImageData(imgData,0,0);
                }
                console.log("end");

            };


            Fill.prototype.isPixelWhite = function(pixelData, pixelPos, r, g, b, a){

                var redCheck = pixelData[pixelPos] == r;
                var greenCheck = pixelData[pixelPos+1] == g;
                var blueCheck = pixelData[pixelPos+2] == b;
                var alphaCheck = pixelData[pixelPos+3] == a;

                if(redCheck && greenCheck && blueCheck && alphaCheck){
                        return true;
                }
                return false;
            };

            Fill.prototype.fill = function (startX, startY, startR, startG, startB, startA,context,pixelData) {

                var drawingAreaWidth = context.canvas.width;
                var drawingAreaHeight = context.canvas.height;

                var newPos,
                    x,
                    y,
                    pixelPos,
                    reachLeft,
                    reachRight,
                    drawingBoundLeft = 0,
                    drawingBoundTop = 0,
                    drawingBoundRight = drawingAreaWidth - 1,
                    drawingBoundBottom = drawingAreaHeight - 1,
                    pixelStack = [[startX, startY]];

                while (pixelStack.length) {

                    newPos = pixelStack.pop();
                    x = newPos[0];
                    y = newPos[1];

                    // Get current pixel position
                    pixelPos = (y * drawingAreaWidth + x) * 4;

                    // Go up as long as the color matches and are inside the canvas
                    while (y >= drawingBoundTop && this.isPixelWhite(pixelData,pixelPos, startR, startG, startB, startA)) {
                        y -= 1;
                        pixelPos -= drawingAreaWidth * 4;
                    }

                    pixelPos += drawingAreaWidth * 4;
                    y += 1;
                    reachLeft = false;
                    reachRight = false;

                    // Go down as long as the color matches and in inside the canvas
                    while (y <= drawingBoundBottom && this.isPixelWhite(pixelData,pixelPos, startR, startG, startB, startA)) {
                        y += 1;

                        this.colorPixel(pixelData,pixelPos);

                        if (x > drawingBoundLeft) {
                            if (this.isPixelWhite(pixelData,pixelPos - 4, startR, startG, startB, startA)) {
                                if (!reachLeft) {
                                    // Add pixel to stack
                                    pixelStack.push([x - 1, y]);
                                    reachLeft = true;
                                }
                            } else if (reachLeft) {
                                reachLeft = false;
                            }
                        }

                        if (x < drawingBoundRight) {
                            if (this.isPixelWhite(pixelData,pixelPos + 4, startR, startG, startB, startA)) {
                                if (!reachRight) {
                                    // Add pixel to stack
                                    pixelStack.push([x + 1, y]);
                                    reachRight = true;
                                }
                            } else if (reachRight) {
                                reachRight = false;
                            }
                        }

                        pixelPos += drawingAreaWidth * 4;
                    }
                }
            };


            Fill.prototype.colorPixel = function (pixelData, pixelPos, a) {

                var pickedColorRGBAArray = this.convertHex(this.color,0);

                pixelData[pixelPos] = pickedColorRGBAArray[0];
                pixelData[pixelPos + 1] = pickedColorRGBAArray[1];
                pixelData[pixelPos + 2] = pickedColorRGBAArray[2];
                pixelData[pixelPos + 3] = a !== undefined ? a : 255;
            };

            Fill.prototype.getClickedColor = function(pixelData, x, y){

                var drawingAreaWidth = context.canvas.width;
                var pixelPos = (y * drawingAreaWidth + x) * 4;

                var retRGB = [];

                retRGB.push(pixelData[pixelPos]);
                retRGB.push(pixelData[pixelPos + 1]);
                retRGB.push(pixelData[pixelPos + 2]);
                retRGB.push(pixelData[pixelPos + 3]);

                return retRGB;
            };


            Fill.prototype.convertHex = function(hex,opacity){
                hex = hex.replace('#','');
                var r = parseInt(hex.substring(0,2), 16);
                var g = parseInt(hex.substring(2,4), 16);
                var b = parseInt(hex.substring(4,6), 16);

                var result = [];
                result.push(r,g,b);
                return result;
            };



                /*
                 Line Class (subclass from Shape)

                 points - list of points
                 void: addPoint() - add point to line

                 */
                var Line = function( x, y, color, lineWidth){
                    Shape.call(this,new Point(x,y), color, lineWidth);
                    this.points = [];
                    this.points.push(this.point);
                };

                Line.prototype = Object.create(Shape.prototype);
                Line.prototype.constructor = Line;

                Line.prototype.addPoint = function (x,y) {
                    this.points.push(new Point(x,y));
                };
                Line.prototype.draw = function(context) {

                    for (var i = 0; i < this.points.length; i++) {

                        context.beginPath();
                        context.strokeStyle = this.color;
                        context.lineCap = "round";
                        context.lineJoin = "round";
                        context.lineWidth = this.lineWidth;

                        if (this.points[i] && i) {
                            context.moveTo(this.points[i - 1].x, this.points[i - 1].y);
                        } else {
                            // The x position is moved over one pixel so a circle even if not dragging
                            context.moveTo(this.points[i].x - 1, this.points[i].y);
                        }
                        context.lineTo(this.points[i].x, this.points[i].y);
                        context.stroke();
                        context.closePath();
                    }
                };
                Line.prototype.drawContour = function(context){
                    this.draw(context);
                };


                /*
                 Rectangle class (subclass of Shape class)
                 */
                var Rectangle = function(x, y, width, height, color, lineWidth){
                    Shape.call(this,new Point(x,y),color, lineWidth);
                    this.width = width;
                    this.height = height;
                };
                Rectangle.prototype = Object.create(Shape.prototype);
                Rectangle.prototype.constructor = Rectangle;
                Rectangle.prototype.draw = function(context){
                    context.fillStyle = this.color;
                    context.lineWidth = this.lineWidth;
                    context.beginPath();
                    context.fillRect(this.point.x,this.point.y,this.width,this.height);
                    context.closePath();
                };
                Rectangle.prototype.drawContour = function(context){
                    context.strokeStyle = this.color;
                    context.lineWidth = this.lineWidth;
                    context.beginPath();
                    context.strokeRect(this.point.x,this.point.y,this.width,this.height);
                    context.closePath();
                };</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="col-md-8 canvas-boards" style="margin-left: -6px;   margin-top: -33px;">
      <canvas id="board" width="438" height="440" style="z-index: 0;"></canvas>
      <canvas id="board2" width="438" height="475" style="z-index: 1;"></canvas>    
    </div></code></pre>
</div>
</div>


//CSS


}
/*---------------------------Cursor --------------------------------*/




.canvas-boards {


    cursor: url('cursor_brush.png')0 130, move;

}

/*---------------------------Drawing Board--------------------------------*/





.container-fluid {


  margin-left: 50%;   
  margin-right: 50%;     

}


///////this is the styling for the div that holds everything including the canvas

#Draw {

 display: none;    
margin-left: 300px;

}



.drawings col-md-2 {

width: 50%;     
margin-right: 50px; 


}

enter code here

.canvas-container  {



}


.thumbnail img {
    height: 80px;
    width: 40px;

}

.canvas-container {

    background-size: 100% 100%;
    background-repeat: no-repeat;
    width: 800px;
    height: 540px;



}

.canvas-container .tools {
    width: 80px;
    margin-left: 45px;
    padding-top: 80px;
    float: left;
}


.canvas-container .drawings {
    width: 200px;
    padding-top: 85px;
    margin-left: 632px;
    float: none;
}





.col-md-8.canvas-boards {
margin-left: -25px; 



}
.canvas-container #board2 {
margin-top: -373px;
margin-left: 35px; 
margin-right: -20px;
width: 438px;
height: 475px;



}
.canvas-container #board {
 margin-top: 68px;
margin-left: 35px; 
margin-right: -19px; 
margin-bottom: -73px;
width: 438px;
height: 440px;

}

最佳答案

这就是我为解决问题所做的工作。谢谢

mouseX = (event.touches !== undefined) ? (event.touches[0].pageX - bRect.left)*(canvas2.width/bRect.width) : event.offsetX || event.pageX-$('#board2').offset().left,

mouseY = (event.touches !== undefined) ? (event.touches[0].pageY - bRect.top)*(canvas2.height/bRect.height) : event.offsetY || event.pageY-$('#board2').偏移量

关于javascript - Canvas Html5 Drawing App,移动 Canvas 导致大问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37329218/

相关文章:

php - PHP邮件功能无法完成电子邮件的发送

具有两个操作的 HTML 按钮。其中之一要延期

html - 我的 div 高度不随背景图像缩放

css - react Material 套件 - 无法向标题添加 Logo

css - 边界半径问题 CSS

javascript - 使 iris 的颜色选择器在未聚焦时消失

jquery - 如何使用 Bootstrap 创建类似 Facebook mobile 的响应式菜单

javascript - 如何标记与文本混合的单词

javascript在确认时更改按钮值

javascript - HtmlUnit net.sourceforge.htmlunit.corejs.javascript.EcmaError : TypeError: Cannot read property "GetLoginJsonInfo" from undefined