Resizing an image with six corners using the canvas technique

Currently, I am facing two issues:

  1. The topcenter, bottomcenter, left and right anchors are not clickable.
  2. I'm struggling with the logic to adjust the image size proportionally as described below:
    1. The corner anchors should resize both height and width simultaneously.
    2. The non-cornered anchors should resize accordingly as illustrated in the provided image.

This is how I envision the implementation:

I've set up a canvas where I draw an image and handle resizing. Here's my simple HTML structure:

<canvas width="700px" height="700px" id="canvas"></canvas>

And here's the accompanying script:

// The JavaScript code 
var canvas = document.getElementById("canvas");
// More script follows...

You can view the actual output here.

I would appreciate it if you could assist me in resolving the issue of the non-cornered anchors being unresponsive and guide me on correctly resizing the image based on the anchor positions as outlined above and demonstrated in the image. Your help would be greatly appreciated. :)

**Note: **I do not have access to jQuery for this task.

Answer №1

Check out my response over here: Changing the origin of a canvas drawn image

I'll also repeat the solution below just in case someone finds this page through Google instead.

An effective method for resizing as desired is to keep one or more sides fixed while allowing another side to be adjusted by dragging a side or corner.

An added advantage of this approach is that you don't necessarily need visible anchors to resize!

This mirrors how operating system windows function.

When you resize windows on your desktop, you typically drag from the side or corner without any visible anchor points to guide you.

Here's a demonstration: http://jsfiddle.net/m1erickson/keZ82/

  • Left: original image,
  • Middle: resized from bottom-left corner with aspect ratio maintained (top-right corner remains unchanged)
  • Right: resized from bottom only, causing vertical scaling exclusively (top edge of image remains stationary)

Please note that although this demo and example show anchors, they are purely cosmetic. You can disable the anchor display and still resize the image by dragging the sides or corners.

Sample code:

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>
<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var $canvas=$("#canvas");
    var canvasOffset=$canvas.offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;
    var isDown=false;

    var iW;
    var iH;
    var iLeft=50;
    var iTop=50;
    var iRight,iBottom,iOrientation;

    var img=new Image();
    img.onload=function(){
        iW=img.width;
        iH=img.height;
        iRight=iLeft+iW;
        iBottom=iTop+iH;
        iOrientation=(iW>=iH)?"Wide":"Tall";
        draw(true);
    }
    img.src="facesSmall.png";

    var border=10;
    var isLeft=false;
    var isRight=false;
    var isTop=false;
    var isBottom=false;
    var iAnchor;

    canvas.onmousedown=handleMousedown;
    canvas.onmousemove=handleMousemove;
    canvas.onmouseup=handleMouseup;
    canvas.onmouseout=handleMouseup;


    function hitResizeAnchor(x,y){

        // determine which borders are under the mouse
        isLeft=(x>iLeft && x<iLeft+border);
        isRight=(x<iRight && x>iRight-border);
        isTop=(y>iTop && y<iTop+border);
        isBottom=(y<iBottom && y>iBottom-border);

        // return the appropriate anchor based on position
        if(isTop && isLeft){ return(iOrientation+"TL"); }
        if(isTop && isRight){ return(iOrientation+"TR"); }
        if(isBottom && isLeft){ return(iOrientation+"BL"); }
        if(isBottom && isRight){ return(iOrientation+"BR"); }
        if(isTop){ return("T"); }
        if(isRight){ return("R"); }
        if(isBottom){ return("B"); }
        if(isLeft){ return("L"); }
        return(null);
    }

    var resizeFunctions={

        T: function(x,y){ iTop=y; },
        R: function(x,y){ iRight=x; },
        B: function(x,y){ iBottom=y; },
        L: function(x,y){ iLeft=x; },

        WideTR: function(x,y){
            iRight=x;
            iTop=iBottom-(iH*(iRight-iLeft)/iW);
        },
        TallTR: function(x,y){
            iTop=y;
            iRight=iLeft+(iW*(iBottom-iTop)/iH);
        },

        WideBR: function(x,y){
            iRight=x;
            iBottom=iTop+(iH*(iRight-iLeft)/iW);
        },
        TallBR: function(x,y){
            iBottom=y;
            iRight=iLeft+(iW*(iBottom-iTop)/iH);
        },

        WideBL: function(x,y){
            iLeft=x;
            iBottom=iTop+(iH*(iRight-iLeft)/iW);
        },
        TallBL: function(x,y){
            iBottom=y;
            iLeft=iRight-(iW*(iBottom-iTop)/iH);
        },

        WideTL: function(x,y){
            iLeft=x;
            iTop=iBottom-(iH*(iRight-iLeft)/iW);
        },
        TallTL: function(x,y){
            iBottom=y;
            iLeft=iRight-(iW*(iBottom-iTop)/iH);
        }
    };

    function handleMousedown(e){
         // indicate that we will handle this mousedown event
         e.preventDefault();
         e.stopPropagation();
         var mouseX=e.clientX-offsetX;
         var mouseY=e.clientY-offsetY;
         iAnchor=hitResizeAnchor(mouseX,mouseY);
         isDown=(iAnchor);
    }

    function handleMouseup(e){
         // indicate that we will handle this mouseup event
         e.preventDefault();
         e.stopPropagation();
         isDown=false;
         draw(true);
    }

    function handleMousemove(e){
         // indicate that we will handle this mousemove event
         e.preventDefault();
         e.stopPropagation();
         // exit if not currently dragging
         if(!isDown){return;}
         // obtain current MouseX/Y coordinates
         var mouseX=e.clientX-offsetX;
         var mouseY=e.clientY-offsetY;

         // update iLeft, iRight, iTop, iBottom based on drag operation
         resizeFunctions[iAnchor](mouseX,mouseY);

         // redraw the resized image
         draw(false);
    }


    function draw(withAnchors){
        var cx=iLeft+(iRight-iLeft)/2;
        var cy=iTop+(iBottom-iTop)/2;
        ctx.clearRect(0,0,canvas.width,canvas.height);
        ctx.drawImage(img,iLeft,iTop,iRight-iLeft,iBottom-iTop);   
        if(withAnchors){
            ctx.fillRect(iLeft,iTop,border,border);
            ctx.fillRect(iRight-border,iTop,border,border);
            ctx.fillRect(iRight-border,iBottom-border,border,border);
            ctx.fillRect(iLeft,iBottom-border,border,border);
            ctx.fillRect(cx,iTop,border,border);
            ctx.fillRect(cx,iBottom-border,border,border);
            ctx.fillRect(iLeft,cy,border,border);
            ctx.fillRect(iRight-border,cy,border,border);
        }
    }

}); // end $(function(){});
</script>
</head>
<body>
    <h4>Adjusting image dimensions</h4>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to assign multiple values to certain elements within an array?

I have an array that looks like this: items = { item1: 10, item2: 5, item3: 7, item4: 3, }; I am looking to include additional details in this array, for example: items = { item1: 10 {available: true}, ...

Encountering an error message that says "ERROR TypeError: Cannot read property 'createComponent' of undefined" while trying to implement dynamic components in Angular 2

I am currently facing an issue with dynamically adding components in Angular 4. I have looked at other similar questions for a solution but haven't been able to find one yet. The specific error message I am getting is: ERROR TypeError: Cannot read ...

Using $anchorScroll in Angular to create an anchor link that links to the same page but with a style change seems to be ineffective

I have a simple Angular view that includes a menu. Each item in the menu serves as a link to a specific section of the same page. I am utilizing $anchorScroll to achieve this functionality and it is functioning correctly. However, I am encountering an issu ...

Changing the .load function based on user input

Can I replace a .load text with one that can be updated by a user using form input or similar method? My goal is to create a code that retrieves data using unique div IDs (specific to each employee) containing information within tables across various HTML ...

Use JQuery to reverse the most recent button click

Here is the code snippet I am working with: <button class="btn">New York</button> <button class="btn">Amsterdam</button> <button class="btn">New Jersey</button> <button class="btn&qu ...

Implementing Github Oauth2 in a Rails server independent from a chrome extension

Looking to implement Github Oauth2 from my chrome extension, but rather than using chrome.identity.launchWebAuthFlow I want to handle it through my server. This way, I can avoid exposing my client ID and Client Secret in the javascript of the extension. My ...

I am facing difficulties in adding dynamic content to my JSON file

I've encountered a challenge in appending new dynamic data to a JSON file. In my project, I receive the projectName from an input form on the /new page. My API utilizes node.js's fs module to generate a new JSON file, where I can subsequently add ...

Determine if the user's request to my website is made through a URL visit or a script src/link href request

Presently, I am working on developing a custom tool similar to Rawgit, as a backup in case Rawgit goes down. Below is the PHP code I have created: <?php $urlquery = $_SERVER['QUERY_STRING']; $fullurl = 'http://' . $_SERVER['SE ...

Creating a personalized message for a failed "Get" request using the HTTPS native module in combination with

Currently, I have implemented an Express application that includes an HTTP GET request to an external API. It functions properly when there are no errors; however, I am looking to customize the response sent to the client-side in case of failures: const ht ...

Utilizing the onscroll feature to trigger a function within a ScrollView

I am facing an issue with an animated view where I need to execute multiple events within the onScroll property. The current onScroll implementation is as follows: onScroll={ Animated.event( [{ nativeEvent: { conten ...

Struggling to get the knockout js remove function to function properly within a nested table structure

I've been encountering issues while trying to eliminate the formulation elements with the 'Delete comp' link. I can't seem to figure out why it's not functioning as expected. Moreover, the 'Add another composition' link o ...

Iframe not displaying Base64 encoded PDF in Chrome App

Currently, I am in the process of developing a Chrome App that essentially acts as a wrapper for the main app within a webview. The webview sends a Base64 encoded PDF as a message to the app, which then creates a hidden iframe and loads the PDF into the fr ...

Transforming color images into black and white using JavaScript

     I have implemented this code to convert colored images to grayscale. function applyGrayscaleEffect() {         var imageData = contextSrc.getImageData(0, 0, width, height);         var data = imageData.data;         var p1 = 0.99;   ...

Creating a header for an HTML table with merged columns in jQuery DataTables

Whenever I attempt to implement the jQuery DataTables plugin, it encounters an error stating c is undefined on line 256 (as seen in the minified version). The structure of my table is as follows: <table class="datatable"> <thead> ...

The sequencing of AJAX calls on the server side may not necessarily match the order in which they were initiated on the client side

I am working on an ASP.NET MVC application that includes a JavaScript function within a view. Here is the code snippet: function OnAmountChanged(s, fieldName, keyValue, url) { console.log("Get Number: " + s.GetNumber()); console.log(" "); ...

Tips for calculating the difference between timestamps and incorporating it into the response using Mongoose

In my attendance model, there is a reference to the class model. The response I receive contains two createdAt dates. const attendanceInfo = await Attendance.find({ student: studentId, }) .populate('class', 'createdAt'); ...

Is it true that event.stopPropagation does not function for pseudoelements?

I am facing an issue with event handling in my ul element. The ul has three li children elements, and the ul itself has a useCapture event handler for click. In the click event handler, I successfully stop the event using event.stopPropagation(), and every ...

v-for based on element type

I'm facing an issue with a basic vue.js application. I have a list of referees and I need to iterate through that list and add data from an ajax request to each item. Strangely, when I try to display the list using v-for on a span element, it works pe ...

Having trouble shutting down Metro Bundler on Windows?

While working on my React Native development, I regularly use npm start to get things going. However, I've run into an issue recently when trying to stop the process using Ctrl + c. It seems like I can no longer use npm start smoothly: ERROR Metro ...

Show each text field individually in JavaScript

Is it possible to display text fields one by one upon button click? Initially, all text fields are hidden, but when the button is clicked, they should be displayed one after another with their visibility property set to visible? This is what I have attemp ...