0

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:

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

    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);
});
Murtaza Raza
  • 3
  • 1
  • 5

3 Answers3

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

This will make sure that the page is loaded before it tries to get the image.

Tyler Dalton
  • 59
  • 1
  • 6
  • Thank you for your answer but the file is already in the same folder as the HTML. – Murtaza Raza Apr 30 '16 at 18:41
  • Still no difference.. I am including the whole js file, maybe there is a problem somewhere else. I would also like to add that Im new to javascript, but I do know java, are there any libraries I have to include that Im missing (or are there libraries?) thank you again – Murtaza Raza Apr 30 '16 at 19:48
0

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.

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.

  <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

  • I tried that but it didnt work again. Maybe I made some other mistake.. Im including the whole js code this time, maybe there is a problem somewhere else? – Murtaza Raza Apr 30 '16 at 19:46
0

I noticed you're using my code from this post. :-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.

  • Wrap the entire script in $(function(){<script>...all the JS code...</script>} so that it loads after the DOM is loaded.

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

  • 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).

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>
Community
  • 1
  • 1
markE
  • 102,905
  • 11
  • 164
  • 176
  • I found your answer (I think) and then followed the javascript fiddle link. First I'd like to apologize for using your code without you permission, the code was supplied already so I thought it wouldnt matter. Secondly, I tried including everything in "$(document).ready(function(){//code here});" and I included jquery (and tested if it really is included) but still the image isn't loading. I don't understand what I'm doing wrong. – Murtaza Raza May 01 '16 at 11:34
  • No apology needed -- if you use code from Stackoverflow you only must give the author attribution and cite the SO Q&A where you got the code. I've added full code made with the changes in my answer. Good luck with your project! – markE May 01 '16 at 15:37
  • Thank you for your help! And I will definitely keep that in mind. – Murtaza Raza May 01 '16 at 19:00