当前位置: 首页 > 知识库问答 >
问题:

画布Html5绘图App,移动画布引发重大问题

於英朗
2023-03-14

我正在创建一个Html5绘图应用程序,我已经解决了所有的功能,但我现在遇到了问题,因为我现在在设计阶段,并试图使它看起来很好。我想居中我的画板,但一旦我实现css到div容器,容器将移动,但它将推动画板/画布出容器,它将离开页面远离我的绘图光标。有没有一种方法让所有的东西都能正确地移动在一起?谢谢你...我提前向你道歉这里有很多代码


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

共1个答案

匿名用户

我就是这么做来解决我的问题的。谢谢

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

mouseY=(事件.触碰!==未定义)?(event.touches[0].pagey-brett.top)*(canvas2.height/brett.height):event.offsety event.pagey-$('#board2').offset

相关问题


  • Spring 引导@Mapper Bean 创建问题:应用程序无法启动。错误:考虑定义一个类型的 bean
  • 无法使用 SpringApplication.exit() 终止 Spring 启动作业应用程序,因为 Tomcat 错误“套接字接受失败”
  • 如何修复Firebase 9.0导入错误?“尝试导入错误:‘Firebase/app’不包含默认导出(导入为‘Firebase’)。”
  • 继承注释-线程“main”org.hubinate.MappingException中的异常:实体的映射中重复列
  • 将异常映射到带有Jersey ExceptionMapper的响应时回滚事务
  • 如何在Eclipse for Google App Engine中从Java7切换到Java6?
  • 使用ObjectMapper JavaTimeModule将JacksonJsonProvider注册到Jersey 2客户端
  • Tycho引发Eclipse IDE没有的错误:无法引用非最终变量
  • Spring boot:在测试中引用application.properties的pom属性
  • 在@ConstructorResult的情况下,将@SqlResultSetMapping放置在何处
  • 使用APPLESCRIPT获取特定进程的CPU使用率
  • 如何在Applescript中移动对话框窗口?
  • Applescript如何显示带有文本和变量的对话框
  • 运行检测显示的Applescript
  • Applescript外壳程序脚本进度
  • 让AppleScript点按按钮“”并选择“语言”,然后点按“添加”
  • 使用AppleScript定位Chrome扩展
  • AppleScript中的Javascript“无法使脚本成为类型说明符”(用于在Chrome中单击按钮)
  • 通过AppleScript设置屏幕共享密码
  • 仅使用Applescript在文件夹“LaunchAgents”中创建一个新plist

共有3个答案

慕容成和
2023-03-14
热门标签
邓正真
2023-03-14
相关问题
康弘义
2023-03-14

我就是这么做来解决我的问题的。谢谢

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

mouseY=(事件.触碰!==未定义)?(event.touches[0].pagey-brett.top)*(canvas2.height/brett.height):event.offsety event.pagey-$('#board2').offset

 类似资料:
  • 实际上,我可以使用函数来完成。我从“HTML5画布-如何在图像背景上画一条线?”中得到的东西。但是我需要在不使用from函数的情况下绘制图像,如下所示:

  • 一直以来,我都在开发一款分辨率为800x480(流行手机分辨率)的应用程序。 我的画布HTML: 现在,为了使其全屏显示其他分辨率,我在调整大小事件后执行以下操作: 这是可行的,但问题是我不能以这种方式保持纵横比。800x480是4:3,但是如果我在5:3的手机上运行这个应用程序,有些东西(尤其是圆圈)看起来会被拉伸。 有没有什么方法可以让它在所有分辨率下看起来都很好,而不必为每个纵横比创建一组独

  • 我编写了这段代码,可以在JavaFX画布上绘制。它可以很好地工作,但我不知道如何重新绘制画布(比如在Swing中),以便在新画布上重新开始绘制。这是我的代码,非常感谢你的帮助!马里奥

  • https://developer.mozilla.org/en/Canvas_tutorial/Transformations http://en.wikipedia.org/wiki/Spirograph 移植一个HTML5画布图像到QML画布非常简单。在成百上千的例子中,我们选择了一个来移植。 螺旋图形(Spiro Graph) 我们使用一个来自Mozila项目的螺旋图形例子来作为我们的基础

  • 我想在画布上画一段视频。为了实现这一点,我在Javascript中捕获onMouseDown和onMouseUp事件,以获得每个事件的x和y坐标(我需要在画布中设置视频的位置、宽度和高度)。 因此,每次我在画布上绘制视频时,我创建的上一个视频都应该停止,并且必须播放新的视频。两个问题: 1)视频不播放(功能只画第一帧),但他的音频可以 2) 如何停止以前绘制的视频? 演示:http://jsfid

  • 有一个代码这行,但我不知道怎么做,我只能做一个2行在这同一时间。