Guide on resizing canvas based on uploaded image using javascript?

Below is the code snippet I am working with:

<script type="text/javascript>
//start pdf to canvas

 ...

//end pdf to canvas
var a="123_m";
var imgname = "images/im/"+a+"/2";

var side = 1;
$(document).ready(function () {
    $("#ImageUpload").uploadify({
        'multi': false,
        'queueSizeLimit': 1,
        'fileSizeLimit': 0,
        'progressData': 'speed',
        'swf': 'upscripts/uploadify.swf',
        'width': 67,
        'height': 50,
        'folder': 'Uploads',
        'auto': true,
        'onUploadError': function (file, errorCode, errorMsg, errorString) {
        },
        'onUploadSuccess': function (file, response) {

            var a = file.name;
            var b = "asdfd";
            angular.element("#canvascontainer").scope().InsertImage(a);
        }
    });

    var canvasdiscription = [{ "objects": [], "background": "rgba(0, 0, 0, 0)", "backgroundImage": "pug.jpg", "backgroundImageOpacity": 1, "backgroundImageStretch": true}];
    canvasdiscription[0].objects.push({ "type": "leg-text", "left": 202, "top": 51, "width": 231, "height": 31.2, "fill": "#000000", "overlayFill": null, "stroke": null, "strokeWidth": 1, "strokeDashArray": null, "scaleX": 1.53, "scaleY": 1.53, "angle": 0, "flipX": false, "flipY": false, "opacity": 1, "selectable": true, "hasControls": true, "hasBorders": true, "hasRotatingPoint": true, "transparentCorners": true, "perPixelTargetFind": false, "text": "0001", "fontSize": 24, "fontWeight": 100, "fontFamily": "Arial", "fontStyle": "", "lineHeight": 1.3, "textDecoration": "", "textShadow": "", "textAlign": "left", "path": null, "strokeStyle": "", "backgroundColor": "", "useNative": true, "name": "text", "lockUniScaling": true, "config": { "feildId": "3", "feildName": "fldcname" }, "validations": { "maxwidth": 700, "maxheight": 400, "maxfont": 1000, "minfont": 0, "angle": 0 }, "controls": { "fontFamily": true, "fontSize": true, "boldFont": true, "normalFont": true, "italicFont": true, "colorFont": true, "groupOperations": true, "addToFront": true, "leftAlign": true, "rightAlign": true, "centerAlign": true, "underLine": true, "reAlign": true }, "originaltext": "0001", "meta": {} });
    alert(imgname);
    canvasdiscription[0].backgroundImage = imgname + "-2.jpg";
    alert(imgname + "-2.jpg");

    var canvasLimit = canvasdiscription.length;
    var canvasData = [];

    var jcrop_api;
    var bounds, boundx, boundy;
    var c = {};
    for (var i = 0; i < canvasdiscription.length; i++)
    {
        var canvas = {};
        canvas.json = canvasdiscription[i];
        alert(canvasdiscription.length);
        canvas.height = 559;
        canvas.width = 397;
        canvas.scaleFactorX = 1; // 0.75714285714286;
        canvas.scaleFactorY = 1; // 0.75714285714286;
        canvas.left = 10;
        canvas.top = 10;
        canvasData.push(canvas);
    }

    console.log(canvasData);

    Start(canvasLimit, canvasData);
    //Initially run the function:
    $(window).resize();
});
</script>

The current issue I am facing in this code is related to resizing the canvas based on the uploaded JPG image. The resizing is not functioning as expected when adjusting it to match the dimensions of the image. I seek assistance in resolving this challenge and appreciate any help provided. Thank you!

Answer №1

After looking into it further, I believe I have found a solution to address your query. As previously mentioned in the comments, there were errors in the previous loop, but my code now seems to align with the corrections needed:

<script type="text/javascript">
    var canvasDescription = [{ "objects": [], "background": "rgba(0, 0, 0, 0)", "backgroundImage": "pug.jpg", "backgroundImageOpacity": 1, "backgroundImageStretch": true}];
    canvasDescription[0].objects.push({ "type": "leg-text", "left": 202, "top": 51, "width": 231, "height": 31.2, "fill": "#000000", "overlayFill": null, "stroke": null, "strokeWidth": 1, "strokeDashArray": null, "scaleX": 1.53, "scaleY": 1.53, "angle": 0, "flipX": false, "flipY": false, "opacity": 1, "selectable": true, "hasControls": true, "hasBorders": true, "hasRotatingPoint": true, "transparentCorners": true, "perPixelTargetFind": false, "text": "0001", "fontSize": 24, "fontWeight": 100, "fontFamily": "Arial", "fontStyle": "", "lineHeight": 1.3, "textDecoration": "", "textShadow": "", "textAlign": "left", "path": null, "strokeStyle": "", "backgroundColor": "", "useNative": true, "name": "text", "lockUniScaling": true, "config": { "feildId": "3", "feildName": "fldcname" }, "validations": { "maxwidth": 700, "maxheight": 400, "maxfont": 1000, "minfont": 0, "angle": 0 }, "controls": { "fontFamily": true, "fontSize": true, "boldFont": true, "normalFont": true, "italicFont": true, "colorFont": true, "groupOperations": true, "addToFront": true, "leftAlign": true, "rightAlign": true, "centerAlign": true, "underLine": true, "reAlign": true }, "originaltext": "0001", "meta": {} });

    var canvasData = [];

    //Iterating through the contained JSON objects in variable 'canvasDescription'
    for (var i = 0; i < canvasDescription.length; i++)
    {
        //Creating a plain JavaScript object
        var objectProperties = eval(canvasDescription[i]);

        //Assuming that the background image will determine the new canvas size
        var imageDimensions = new Image()
        imageDimensions.src = canvasDescription[i].backgroundImage;

        //Iterating through the JSON objects within variable 'canvasDescription.objects',
        //since the property 'objects' contains a list of data in JSON format
        for (var j = 0; j < objectProperties.objects.length; j++)
        {
            //In this example, the following lines adjust the original values
            objectProperties.objects[j].height = imageDimensions.height;
            objectProperties.objects[j].width = imageDimensions.width; 
            objectProperties.objects[j].scaleFactorX = 1; // 0.75714285714286;
            objectProperties.objects[j].scaleFactorY = 1; // 0.75714285714286;
            objectProperties.objects[j].left = 10;
            objectProperties.objects[j].top = 10;

            //Storing the current item in an array
            canvasData.push(objectProperties.objects[j]);
        }
    }

    //Sample output
    console.log("height: " + canvasDescription[0].objects[0].height);
    console.log("top: " + canvasDescription[0].objects[0].top);
    console.log("scaleFactorX: " + canvasDescription[0].objects[0].scaleFactorX);
</script>

This updated version should hopefully be more effective for you.

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

Capture the content from a paragraph element and save it into a variable

Is there a way in VueJS to extract the text from a p tag and save it into a variable? Currently, the text is just displayed inside the p tag, but I want to store it in a variable for future use. Here is the HTML code I am working with: <b-form-input ...

Error: VueQuill Vue3 encountered an issue while trying to read properties of undefined with the message "emit"

Incorporating VueQuill into my vue3 application is resulting in the following console error when attempting to display an HTML string - https://i.stack.imgur.com/KGQqD.png This is my code snippet: <template> <div class=""> & ...

The error message "Element is not defined (Object.<anonymous>)" is occurring in the context of Intro.js-react, React, Next.js, and Tailwind

Here is a code snippet: import { useState } from 'react'; import { Steps } from 'intro.js-react'; export default function Dashboard() { const [stepEnabled, setStepEnabled] = useState(true); const steps = [ { intro: &apos ...

The JWT authentication appears to be functioning properly when tested on "postman," however, it is encountering issues on the website

When I attempt to verify a user's authentication using tools such as "Postman" or "Insomnia," everything functions correctly (when I set the bearer). However, when I try to log in through the website, I encounter an error here: function authenticateT ...

Choosing items by pressing "shift + up arrow"

I have a collection of elements, each representing one line of text. When you click on an element, it changes color. If you then hold down "shift + arrow up," the items above it are also selected. How can this functionality be implemented? My initial app ...

From jQuery to HTML to PHP, then back to HTML from PHP through jQuery

Hey, I have a code snippet that I'm working on: <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script> <script type="text/javascript"> function get() { $.post(' ...

Tips on allowing a rectangle to be draggable using HTML5

I have been experimenting with resizable and draggable rectangles in HTML5. I've managed to create resizable rectangles, but I am having trouble getting them to drag using mouse events. You can view my JSFiddle code at the following link: here. / ...

Is it possible to load a script conditionally in Angular 2 using the Angular CLI

Is it possible to conditionally load scripts using Angular CLI? I am looking to dynamically load a script in this file based on the environment or a variable. For example, I want to load a specific script in production but not in development. How can I ac ...

Configuring the IntelliJ debugger to allow for breaking inside or stepping through an NPM script

I am utilizing an NPM script that executes and produces a file within the repository. Could you please guide me on setting up the debugger to run the script in a way that allows me to perform actions like breaking inside of it and stepping through its cod ...

Extension in Chrome operating in the background while the pop-up is out of sight

As a beginner, my goal was to develop a Chrome Extension. However, I am facing a roadblock as I am unsure how to set up my extension to run in the background. Despite conducting research to find a solution, I have been unable to find a suitable answer to ...

Is it possible to eliminate the default placeholder text from Safari browser?

My goal is to design a form that includes date and time input fields. The placeholder text should move up by X pixels when the user clicks on the field. While the form appears fine in Chrome, there seems to be an issue with overlapping form fields in Safa ...

What is the process for retrieving the array of points from a polygon shape?

My current challenge involves working with a JSON file containing an array of states and a sub-array of corresponding latitude (lat) and longitude (lng) values. After looping through the states and points to build 50 polygons, I now need to center and zoo ...

Ways to delete an element from an array in MongoDB

I am a beginner in the MEAN stack development. I am currently working on implementing this and this. I have been using the $pull method, but it seems that it is not working for me. I suspect that the issue might be due to the differences in my MongoDB stru ...

The functionality of React-router-dom protected routes seems to be malfunctioning

Understanding Protected Routes in React.js: While looking at the implementation of protected routes, you may notice that 'false' is being directly used in the if statement. However, even with this condition, the page is still accessible. Why doe ...

Using regular expressions to replace all special characters, excluding dots

$('#price').keyup(function(){ $('#price').val($('#price').val().replace(/[_\W]+/g, "-")); }) Experience it firsthand here: http://jsfiddle.net/2KRHh/6/. In the scenario above, special characters are eliminated. ...

Personalizing a directive to prevent users from entering special characters in AngularJS

I am currently diving deep into the world of AngularJS directives. My current project involves using a directive to prevent users from inputting special characters. Below is the code snippet: HTML <input type="text" no-special-char ng-model="vm.custo ...

Changing the time format from hh:mm:ss to GMT in an Angular 2 application

Given Input:- Current time: 21:00:00 Desired Output:- Updated time: Wed Dec 20th, 2017 9:00pm GMT+0530 (IST) OR Updated time: 2017-12-20 21:00:00 ...

Learn how to send multiple checkbox values using jQuery and AJAX requests

When trying to extract the value from multiple checkboxes, I utilize this particular code snippet: <form class="myform" method="post" action=""> <input type="checkbox" class="checkbox" value="11" /><br> <input type="ch ...

Automatically activate a button when it comes into view while scrolling

I am currently working in Joomla, which makes it challenging to create a fiddle, but here is the concept: My website displays a mosaic grid of 12 articles upon loading, along with a 'Load More' button. When this button is clicked, an additional ...

The $route object in vue-router appears to be empty when used with single file components

I am facing an issue while using single file components with vue-router and vue-2.0. The problem I can't seem to resolve is that the this.$route object, when called from a component, always returns empty values. For example: https://i.sstatic.net/ws ...