简体   繁体   English

图片未载入HTML画布

[英]Image not loading in HTML canvas

I have a code that is used to re-size and drag/drop an image within the canvas. 我有一个用于在画布内调整大小和拖放图像的代码。 The problem is the image won't show. 问题是图像无法显示。 I have seen this code in other websites and it works for them (apparently), is there anything that I'm doing wrong? 我在其他网站上看到过此代码,并且对他们有用(显然),我在做错什么吗?

I have tried making the image resolution smaller than the canvas' but still to no avail. 我试图将图像分辨率比画布小,但仍然无济于事。

Following is my HTML: 以下是我的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>

Following is my js: 以下是我的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);
});
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);

This will make sure that the page is loaded before it tries to get the image. 这将确保在尝试获取图像之前已加载页面。

One problem could be that the DOM is not ready yet, the html canvas loads before the Javascript but the script has not been run. 一个问题可能是DOM尚未准备就绪,html画布在Javascript之前加载,但脚本尚未运行。

One way is to call a method for 一种方法是为

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

   } ;

Or you could put the entire script code into a function like this. 或者,您可以将整个脚本代码放入这样的函数中。

function callThisOnload (){

     //put all the javascript in here

}

Then place in the body tag the callThisOnload () function like this. 然后将如下所示的callThisOnload()函数放置在body标签中。

  <body onload="callThisOnload ()">

This will let the code run immediately when the DOM is loaded and the the image will be loaded into the canvas 这将使代码在加载DOM时立即运行,并将图像加载到画布中

I noticed you're using my code from this post . 我注意到你用我的代码从这个职位 :-p :-p

  • Load the entire script after the window is loaded. 加载窗口后,加载整个脚本 To do that...don't wrap just part of the code in that init wrapper and don't use that window.onload listener. 为此,...不要只将部分代码包装在该init包装器中,也不要使用该window.onload侦听器。

  • Wrap the entire script in $(function(){<script>...all the JS code...</script>} so that it loads after the DOM is loaded. 整个脚本包装在$(function(){<script>...all the JS code...</script>}以便在加载DOM之后加载。

  • The script requires jQuery -- I don't see where you loaded it so include jQuery: <script src = "https://code.jquery.com/jquery-2.1.1.min.js"></script> 该脚本需要jQuery-我看不到它的加载位置,因此请包含jQuery: <script src = "https://code.jquery.com/jquery-2.1.1.min.js"></script>

  • Make sure your image file (Newzeign.jpg) is in the same folder as this the webpage code (.html, .css, .js AND Newzeign.jpg all in the same folder). 确保图像文件(Newzeign.jpg)与网页代码位于同一文件夹中(.html,.css,.js和Newzeign.jpg都位于同一文件夹中)。

Here's refactored (verified working) code: 这是重构的(验证有效的)代码:

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

Here's a working demo: 这是一个工作示例:

  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); } } 
 body{ background-color: ivory; padding:10px; } #canvas{border:1px solid red;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <canvas id="canvas" width=350 height=350></canvas> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM