图像未在HTML画布中加载

时间:2016-04-30 10:56:17

标签: javascript html5 image canvas html5-canvas

我有一个代码,用于在画布中重新调整大小和拖放图像。 问题是图像不会显示。我在其他网站上看过这个代码,它对他们有用(显然),有什么我做错了吗?

我尝试使图像分辨率小于画布,但仍无济于事。

以下是我的HTML:

<head>
    <script src="resizing.js"></script>
    <style>
    body {
    background-color: ivory;
    padding:10px;
}
</head>
<body>
<canvas id="canvas" width=350 height=350></canvas>
</body>

以下是我的js:

    var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var canvasOffset = $("#canvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;

var startX;
var startY;
var isDown = false;


var pi2 = Math.PI * 2;
var resizerRadius = 8;
var rr = resizerRadius * resizerRadius;
var draggingResizer = {
    x: 0,
    y: 0
};
var imageX = 50;
var imageY = 50;
var imageWidth, imageHeight, imageRight, imageBottom;
var draggingImage = false;
var startX;
var startY;



var init = function(){
var img = new Image();
img.onload = function () {
    imageWidth = img.width;
    imageHeight = img.height;
    imageRight = imageX + imageWidth;
    imageBottom = imageY + imageHeight
    draw(true, false);
}
img.src = "Newzeign.jpg";
};
window.addEventListener("load",init);

function draw(withAnchors, withBorders) {

    // clear the canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // draw the image
    ctx.drawImage(img, 0, 0, img.width, img.height, imageX, imageY, imageWidth, imageHeight);

    // optionally draw the draggable anchors
    if (withAnchors) {
        drawDragAnchor(imageX, imageY);
        drawDragAnchor(imageRight, imageY);
        drawDragAnchor(imageRight, imageBottom);
        drawDragAnchor(imageX, imageBottom);
    }

    // optionally draw the connecting anchor lines
    if (withBorders) {
        ctx.beginPath();
        ctx.moveTo(imageX, imageY);
        ctx.lineTo(imageRight, imageY);
        ctx.lineTo(imageRight, imageBottom);
        ctx.lineTo(imageX, imageBottom);
        ctx.closePath();
        ctx.stroke();
    }

}

function drawDragAnchor(x, y) {
    ctx.beginPath();
    ctx.arc(x, y, resizerRadius, 0, pi2, false);
    ctx.closePath();
    ctx.fill();
}

function anchorHitTest(x, y) {

    var dx, dy;

    // top-left
    dx = x - imageX;
    dy = y - imageY;
    if (dx * dx + dy * dy <= rr) {
        return (0);
    }
    // top-right
    dx = x - imageRight;
    dy = y - imageY;
    if (dx * dx + dy * dy <= rr) {
        return (1);
    }
    // bottom-right
    dx = x - imageRight;
    dy = y - imageBottom;
    if (dx * dx + dy * dy <= rr) {
        return (2);
    }
    // bottom-left
    dx = x - imageX;
    dy = y - imageBottom;
    if (dx * dx + dy * dy <= rr) {
        return (3);
    }
    return (-1);

}


function hitImage(x, y) {
    return (x > imageX && x < imageX + imageWidth && y > imageY && y < imageY + imageHeight);
}


function handleMouseDown(e) {
    startX = parseInt(e.clientX - offsetX);
    startY = parseInt(e.clientY - offsetY);
    draggingResizer = anchorHitTest(startX, startY);
    draggingImage = draggingResizer < 0 && hitImage(startX, startY);
}

function handleMouseUp(e) {
    draggingResizer = -1;
    draggingImage = false;
    draw(true, false);
}

function handleMouseOut(e) {
    handleMouseUp(e);
}

function handleMouseMove(e) {

    if (draggingResizer > -1) {

        mouseX = parseInt(e.clientX - offsetX);
        mouseY = parseInt(e.clientY - offsetY);

        // resize the image
        switch (draggingResizer) {
            case 0:
                //top-left
                imageX = mouseX;
                imageWidth = imageRight - mouseX;
                imageY = mouseY;
                imageHeight = imageBottom - mouseY;
                break;
            case 1:
                //top-right
                imageY = mouseY;
                imageWidth = mouseX - imageX;
                imageHeight = imageBottom - mouseY;
                break;
            case 2:
                //bottom-right
                imageWidth = mouseX - imageX;
                imageHeight = mouseY - imageY;
                break;
            case 3:
                //bottom-left
                imageX = mouseX;
                imageWidth = imageRight - mouseX;
                imageHeight = mouseY - imageY;
                break;
        }

        if(imageWidth<25){imageWidth=25;}
        if(imageHeight<25){imageHeight=25;}

        // set the image right and bottom
        imageRight = imageX + imageWidth;
        imageBottom = imageY + imageHeight;

        // redraw the image with resizing anchors
        draw(true, true);

    } else if (draggingImage) {

        imageClick = false;

        mouseX = parseInt(e.clientX - offsetX);
        mouseY = parseInt(e.clientY - offsetY);

        // move the image by the amount of the latest drag
        var dx = mouseX - startX;
        var dy = mouseY - startY;
        imageX += dx;
        imageY += dy;
        imageRight += dx;
        imageBottom += dy;
        // reset the startXY for next time
        startX = mouseX;
        startY = mouseY;

        // redraw the image with border
        draw(false, true);

    }


}


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

$("#canvas").mouseout(function (e) {
    handleMouseOut(e);
});

3 个答案:

答案 0 :(得分:0)

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

// I cut out the rest of the code to make answer shorter...

var init = function()
{
     var img = new Image();
     img.onload = function ()
     {
            imageWidth = img.width;
        imageHeight = img.height;
        imageRight = imageX + imageWidth;
        imageBottom = imageY + imageHeight
        draw(true, false);
    }
    img.src = "Newzeign.jpg";
};
window.addEventListener("load",init);

这将确保在尝试获取图像之前加载页面。

答案 1 :(得分:0)

一个问题可能是DOM尚未就绪,html画布在Javascript之前加载但脚本尚未运行。

一种方法是为

调用方法
document. onload=function (){
    var img = new Image();
    img.onload = function () {
    imageWidth = img.width;
    imageHeight = img.height;
     imageRight = imageX + imageWidth;
    imageBottom = imageY + imageHeight
     draw(true, false);
}
img.src = "Newzeign.jpg";

   } ;

或者您可以将整个脚本代码放入这样的函数中。

function callThisOnload (){

     //put all the javascript in here

}

然后在body标签中放置callThisOnload()函数,就像这样。

  <body onload="callThisOnload ()">

这将使代码在加载DOM时立即运行,并且图像将加载到画布

答案 2 :(得分:0)

我注意到您正在使用this post中的代码。 :-P

  • 加载窗口后加载整个脚本。要做到这一点......不要在init包装器中包装部分代码,也不要使用window.onload监听器。

  • $(function(){<script>...all the JS code...</script>}中包装整个脚本,以便在加载DOM后加载。

  • 该脚本需要jQuery - 我不知道你在哪里加载它所以包括jQuery:<script src = "https://code.jquery.com/jquery-2.1.1.min.js"></script>

  • 确保您的图片文件(Newzeign.jpg)与网页代码(.html,.css,.js和Newzeign.jpg都位于同一文件夹中)位于同一文件夹中。

以下重构(已验证的工作)代码:

<!doctype html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<style>
    body{ background-color: ivory; padding:10px; }
    #canvas{border:1px solid red;}
</style>
<script>
$(function(){
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");

    var canvasOffset = $("#canvas").offset();
    var offsetX = canvasOffset.left;
    var offsetY = canvasOffset.top;
    var startX;
    var startY;
    var isDown = false;

    var pi2 = Math.PI * 2;
    var resizerRadius = 8;
    var rr = resizerRadius * resizerRadius;
    var draggingResizer = {
        x: 0,
        y: 0
    };
    var imageX = 50;
    var imageY = 50;
    var imageWidth, imageHeight, imageRight, imageBottom;
    var draggingImage = false;
    var startX;
    var startY;

    var img = new Image();
    img.onload = function () {
        imageWidth = img.width;
        imageHeight = img.height;
        imageRight = imageX + imageWidth;
        imageBottom = imageY + imageHeight
        draw(true, false);
    }
    img.src = "https://dl.dropboxusercontent.com/u/139992952/multple/flower.png";

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

    //////////////////////////////////////////////

    function draw(withAnchors, withBorders) {
        // clear the canvas
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // draw the image
        ctx.drawImage(img, 0, 0, img.width, img.height, imageX, imageY, imageWidth, imageHeight);

        // optionally draw the draggable anchors
        if (withAnchors) {
            drawDragAnchor(imageX, imageY);
            drawDragAnchor(imageRight, imageY);
            drawDragAnchor(imageRight, imageBottom);
            drawDragAnchor(imageX, imageBottom);
        }

        // optionally draw the connecting anchor lines
        if (withBorders) {
            ctx.beginPath();
            ctx.moveTo(imageX, imageY);
            ctx.lineTo(imageRight, imageY);
            ctx.lineTo(imageRight, imageBottom);
            ctx.lineTo(imageX, imageBottom);
            ctx.closePath();
            ctx.stroke();
        }
    }

    function drawDragAnchor(x, y) {
        ctx.beginPath();
        ctx.arc(x, y, resizerRadius, 0, pi2, false);
        ctx.closePath();
        ctx.fill();
    }

    function anchorHitTest(x, y) {
        var dx, dy;

        // top-left
        dx = x - imageX;
        dy = y - imageY;
        if (dx * dx + dy * dy <= rr) { return (0); }
        // top-right
        dx = x - imageRight;
        dy = y - imageY;
        if (dx * dx + dy * dy <= rr) { return (1); }
        // bottom-right
        dx = x - imageRight;
        dy = y - imageBottom;
        if (dx * dx + dy * dy <= rr) { return (2); }
        // bottom-left
        dx = x - imageX;
        dy = y - imageBottom;
        if (dx * dx + dy * dy <= rr) { return (3); }
        return (-1);
    }

    function hitImage(x, y) {
        return (x > imageX && x < imageX + imageWidth && y > imageY && y < imageY + imageHeight);
    }

    function handleMouseDown(e) {
        startX = parseInt(e.clientX - offsetX);
        startY = parseInt(e.clientY - offsetY);
        draggingResizer = anchorHitTest(startX, startY);
        draggingImage = draggingResizer < 0 && hitImage(startX, startY);
    }

    function handleMouseUp(e) {
        draggingResizer = -1;
        draggingImage = false;
        draw(true, false);
    }

    function handleMouseOut(e) {
        handleMouseUp(e);
    }

    function handleMouseMove(e) {
        if (draggingResizer > -1) {

            mouseX = parseInt(e.clientX - offsetX);
            mouseY = parseInt(e.clientY - offsetY);

            // resize the image
            switch (draggingResizer) {
                case 0:
                    //top-left
                    imageX = mouseX;
                    imageWidth = imageRight - mouseX;
                    imageY = mouseY;
                    imageHeight = imageBottom - mouseY;
                    break;
                case 1:
                    //top-right
                    imageY = mouseY;
                    imageWidth = mouseX - imageX;
                    imageHeight = imageBottom - mouseY;
                    break;
                case 2:
                    //bottom-right
                    imageWidth = mouseX - imageX;
                    imageHeight = mouseY - imageY;
                    break;
                case 3:
                    //bottom-left
                    imageX = mouseX;
                    imageWidth = imageRight - mouseX;
                    imageHeight = mouseY - imageY;
                    break;
            }

            if(imageWidth<25){imageWidth=25;}
            if(imageHeight<25){imageHeight=25;}

            // set the image right and bottom
            imageRight = imageX + imageWidth;
            imageBottom = imageY + imageHeight;

            // redraw the image with resizing anchors
            draw(true, true);

        } else if (draggingImage) {

            imageClick = false;

            mouseX = parseInt(e.clientX - offsetX);
            mouseY = parseInt(e.clientY - offsetY);

            // move the image by the amount of the latest drag
            var dx = mouseX - startX;
            var dy = mouseY - startY;
            imageX += dx;
            imageY += dy;
            imageRight += dx;
            imageBottom += dy;
            // reset the startXY for next time
            startX = mouseX;
            startY = mouseY;

            // redraw the image with border
            draw(false, true);
        }
    }

}); // end $(function(){});
</script>
</head>
<body>
    <canvas id="canvas" width=350 height=350></canvas>
</body>
</html>

这是一个有效的演示:

&#13;
&#13;
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");

        var canvasOffset = $("#canvas").offset();
        var offsetX = canvasOffset.left;
        var offsetY = canvasOffset.top;
        var startX;
        var startY;
        var isDown = false;

        var pi2 = Math.PI * 2;
        var resizerRadius = 8;
        var rr = resizerRadius * resizerRadius;
        var draggingResizer = {
          x: 0,
          y: 0
        };
        var imageX = 50;
        var imageY = 50;
        var imageWidth, imageHeight, imageRight, imageBottom;
        var draggingImage = false;
        var startX;
        var startY;

        var img = new Image();
        img.onload = function() {
          imageWidth = img.width;
          imageHeight = img.height;
          imageRight = imageX + imageWidth;
          imageBottom = imageY + imageHeight
          draw(true, false);
        }
        img.src = "https://dl.dropboxusercontent.com/u/139992952/multple/flower.png";

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

         //////////////////////////////////////////////

        function draw(withAnchors, withBorders) {
          // clear the canvas
          ctx.clearRect(0, 0, canvas.width, canvas.height);

          // draw the image
          ctx.drawImage(img, 0, 0, img.width, img.height, imageX, imageY, imageWidth, imageHeight);

          // optionally draw the draggable anchors
          if (withAnchors) {
            drawDragAnchor(imageX, imageY);
            drawDragAnchor(imageRight, imageY);
            drawDragAnchor(imageRight, imageBottom);
            drawDragAnchor(imageX, imageBottom);
          }

          // optionally draw the connecting anchor lines
          if (withBorders) {
            ctx.beginPath();
            ctx.moveTo(imageX, imageY);
            ctx.lineTo(imageRight, imageY);
            ctx.lineTo(imageRight, imageBottom);
            ctx.lineTo(imageX, imageBottom);
            ctx.closePath();
            ctx.stroke();
          }
        }

        function drawDragAnchor(x, y) {
          ctx.beginPath();
          ctx.arc(x, y, resizerRadius, 0, pi2, false);
          ctx.closePath();
          ctx.fill();
        }

        function anchorHitTest(x, y) {
          var dx, dy;

          // top-left
          dx = x - imageX;
          dy = y - imageY;
          if (dx * dx + dy * dy <= rr) {
            return (0);
          }
          // top-right
          dx = x - imageRight;
          dy = y - imageY;
          if (dx * dx + dy * dy <= rr) {
            return (1);
          }
          // bottom-right
          dx = x - imageRight;
          dy = y - imageBottom;
          if (dx * dx + dy * dy <= rr) {
            return (2);
          }
          // bottom-left
          dx = x - imageX;
          dy = y - imageBottom;
          if (dx * dx + dy * dy <= rr) {
            return (3);
          }
          return (-1);
        }

        function hitImage(x, y) {
          return (x > imageX && x < imageX + imageWidth && y > imageY && y < imageY + imageHeight);
        }

        function handleMouseDown(e) {
          startX = parseInt(e.clientX - offsetX);
          startY = parseInt(e.clientY - offsetY);
          draggingResizer = anchorHitTest(startX, startY);
          draggingImage = draggingResizer < 0 && hitImage(startX, startY);
        }

        function handleMouseUp(e) {
          draggingResizer = -1;
          draggingImage = false;
          draw(true, false);
        }

        function handleMouseOut(e) {
          handleMouseUp(e);
        }

        function handleMouseMove(e) {
          if (draggingResizer > -1) {

            mouseX = parseInt(e.clientX - offsetX);
            mouseY = parseInt(e.clientY - offsetY);

            // resize the image
            switch (draggingResizer) {
              case 0:
                //top-left
                imageX = mouseX;
                imageWidth = imageRight - mouseX;
                imageY = mouseY;
                imageHeight = imageBottom - mouseY;
                break;
              case 1:
                //top-right
                imageY = mouseY;
                imageWidth = mouseX - imageX;
                imageHeight = imageBottom - mouseY;
                break;
              case 2:
                //bottom-right
                imageWidth = mouseX - imageX;
                imageHeight = mouseY - imageY;
                break;
              case 3:
                //bottom-left
                imageX = mouseX;
                imageWidth = imageRight - mouseX;
                imageHeight = mouseY - imageY;
                break;
            }

            if (imageWidth < 25) {
              imageWidth = 25;
            }
            if (imageHeight < 25) {
              imageHeight = 25;
            }

            // set the image right and bottom
            imageRight = imageX + imageWidth;
            imageBottom = imageY + imageHeight;

            // redraw the image with resizing anchors
            draw(true, true);

          } else if (draggingImage) {

            imageClick = false;

            mouseX = parseInt(e.clientX - offsetX);
            mouseY = parseInt(e.clientY - offsetY);

            // move the image by the amount of the latest drag
            var dx = mouseX - startX;
            var dy = mouseY - startY;
            imageX += dx;
            imageY += dy;
            imageRight += dx;
            imageBottom += dy;
            // reset the startXY for next time
            startX = mouseX;
            startY = mouseY;

            // redraw the image with border
            draw(false, true);
          }
        }
&#13;
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<canvas id="canvas" width=350 height=350></canvas>
&#13;
&#13;
&#13;