In Vue, the CropperJs image initially appears small, but it returns to its original size after editing

I encountered a peculiar issue while working on a website for image cropping using Vue.js and CropperJs. On the homepage, users can select an image to crop and proceed to the next page where a component named ImageCropper.vue is displayed. Strangely, the canvas appears tiny initially. However, when I made a slight modification to the HTML (such as adding a blank line), the image resized itself correctly.

ImageCropper.vue

<template>
    <div class="image-container">
        <img ref="image" :src="source">

    </div>
</template>

<script>
import Cropper from 'cropperjs'

export default {
    name: "ImageCropper",
    props: ["source"],

    data() {
        return {
            cropper: null,
            imageElement: null
        }
    },

    mounted() {
        this.imageElement = this.$refs.image
        this.cropper = new Cropper(this.imageElement, {
                aspectRatio: 1 
        })

    }
}
</script>

Original template view: https://i.stack.imgur.com/5woRw.png

Modified template view (after adding a blank line): https://i.stack.imgur.com/h6THB.png

I attempted to style it with CSS without success. Perhaps my Vue implementation has an issue? This project uses Vue with Vuetify components.

Answer №1

Encountered an issue where the cropper was initialized while its container was not visible due to the use of Vuetify's stepper. The cropping functionality only appeared after the user clicked on "continue", before which it had display: none. Upon editing, the cropper became visible and was re-initialized when its container was visible, resulting in normal rendering (using hot reloading with Vue CLI). Although I cannot pinpoint the exact cause of this behavior, I am confident it is not an error in my code. It is possible that Cropperjs and Vuetify's stepper may not be fully compatible. To resolve this, I added a `continueClicked` property to my Vuex state with a default value of false. I then attached a click listener to the initial Continue button to set `continueClicked` in Vuex to true. Finally, I used the directive v-if="continueClicked" in the ImageCropper.vue component like this:

<ImageCropper v-if="continueClicked" />
. This ensures that the cropper is rendered only when the Continue button is clicked and `continueClicked` is set to true, making it visible when its container is visible.

Answer №2

If you're looking for a solution, consider using the vue-cropperjs wrapper.

<template>
 <div>
   <vue-cropper ref="cropper" :src="imageSource" alt="Image Source"></vue-cropper>
   <v-btn @click="saveImage">Save</v-btn>
 </div>
</template>
<script>
  import VueCropper from 'vue-cropperjs';
  import 'cropperjs/dist/cropper.css';

  export default{
    name: "CroppingComponent",
    components: {
            VueCropper
    },
    data() {
      return {
        imageSource: ''
      }
    },
    methods: {
      saveImage: function(){
        this.$refs.cropper.getCroppedCanvas().toBlob((blob) => {

          //Do something with the blob, like attaching it to form data and sending it to the server
          const formData = new FormData();
          formData.append("type", "profile");
          formData.append('file', blob, this.fileName);

        });
      }
    }
  }
</script>

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 access a component's value from a different component in Vue script?

I have two Vue components in my PHP file: "application" and "vn" component. I am trying to fetch {{obj.vacancies_left}} from the "vn" component and use it in the "application" component. However, I keep getting an undefined variable error. I attempted to r ...

Error in Mathquill: Unable to access the 'prototype' property because it is undefined

I'm currently in the process of integrating MathQuill into a project I'm developing. After installing the package through NPM (npm install mathquill), I included the following <script> tags in the <head>: <script src="../node_ ...

The dynamic links in Knockout.js are unresponsive to clicks

I've been working on a new project that utilizes knockout js. The main issue I'm facing is with setting up a table to display images and information from a form, being stored in an observable array. Each image is wrapped in an anchor tag, and the ...

Trigger the Modal once the navigation step is completed

When navigating to a new page, I need to wait for the navigation process to complete in order for the modal template to be properly displayed on the destination page. public onOpenModal(item) { this.router.navigate([item.link]).then(() => { this. ...

What techniques can be used to maintain the value of 'this' when utilizing async.apply?

Employing async.parallel to simultaneously run 2 functions, initiated from a static function within a mongoose model. In this code snippet (where the model contains a static function named verifyParent), I utilize this to access the model and its functions ...

i am trying to execute a function in an angularjs controller through html, but the scope variable that i am

Being new to angularjs, I'm looking to understand the process of calling a function defined in a controller from HTML within angularjs. I have written the following code in my HTML: First.html <input type="text" ng-model="model.name" name="name ...

Is it possible to use Javascript to gradually fade in text, one word at a time, with multiple divs instead of just one?

I am attempting to gradually fade in individual words from a div. While the code below works fine for a single div, it does not execute sequentially when multiple divs are involved. Here is the fiddle : http://jsfiddle.net/zlud/6czap/110/ Can anyone spot ...

Creating a Vue equation that utilizes props to dynamically assign a class

I am trying to dynamically apply a class to a data table based on the data being passed to it. Although I can successfully run the equation in the template, I'm having trouble figuring out how to do so within the bound class. Let me show you what my ...

TimePicker Component for ASP.Net MVC with Razor Syntax

I'm currently working on implementing a TimePicker using Razor and JQueryUI in my bootstrap website. While I have successfully created a DatePicker, I am facing difficulties in creating a separate TimePicker using two different TextBoxes instead of se ...

Terminate child process with specified user ID using the Forever-monitor

Whenever I need to create new child node processes, I use the following code: var forever = require('forever-monitor'); function startNodeProcess(envVariables, jsFileName, uid) { var child = new (forever.Monitor)(jsFileName, { ...

Angular 2 can efficiently generate multiple HTTP requests simultaneously from a single HTTP request

Backend API's: url: [ { "name": "ABC", "occupation": "Student", "address_url": "http://www.sample.com/address/person=hgjgjgyyfhg" }, { "name": "ABC1", "occupation": "Carpenter", "address ...

Steps for adjusting the status of an interface key to required or optional in a dynamic manner

Imagine a scenario where there is a predefined type: interface Test { foo: number; bar?: { name: string; }; } const obj: Test; // The property 'bar' in the object 'obj' is currently optional Now consider a situatio ...

Attempting to replicate the functionality of double buffering using JavaScript

In my HTML project, I have a complex element that resembles a calendar, with numerous nested divs. I need to refresh this view in the background whenever there are updates on the server. To achieve this, I set up an EventSource to check for data changes on ...

Incorporating JavaScript Object-Oriented Programming in PHP

As someone new to JS programming, I am tasked with developing a php web application that relies on ajax calls for all actions without reloading the page. While I have completed the php and JS code, I am struggling to understand what JS OOP entails. My coun ...

problems encountered when including next.config.js for sitemap creation in a nextjs application

Just recently, I made an update to my next.config.json file in hopes of boosting SEO performance. However, this change has caused some issues with the next-sitemap module, preventing me from building or starting my app. //next.config.js const withSitemap = ...

Adjusting the amount of rows and columns in a fluid manner with CSS grid (updated)

After conducting my research, it seems that the most effective way to set the final value of a CSS grid is either by directly specifying it or by creating/manipulating the css :root value. A similar query was previously raised here, although the answers p ...

The function to navigate, 'navTo', is not defined and so it cannot be read

I am trying to create a navigation button in my SAPUI5 application deployed on Fiori _onPageNavButtonPress: function () { var oHistory = History.getInstance(); var sPreviousHash = oHistory.getPreviousHash(); if (sPreviousHash !== ...

Encountering an error when integrating my library with MUI

Currently, I am working on developing a library that wraps MUI. One of the components I created is a Button, and here is the code snippet for it: import React, { ReactNode } from 'react' import Button from '@mui/material/Button'; impor ...

A guide to testing window.pageYoffset in webdriverIO using chai assertions

When conducting a selenium test using WebDriverIO and Chai, I encountered the need to capture the position of window.pageYoffset. Unfortunately, I was unable to find a direct way to do this in WebDriverIO. My initial attempts involved: browser.scroll(0, 2 ...

Guide on efficiently inserting values into an array of objects

I'm looking to extract specific values from the enum below enum p { XDR = 1, PT1M = 2, PT1M_ = 2, PT5M = 3, PT5M_ = 3, PT15M = 4, PT15M_ = 4, PT1H = 5, PT1H_ = 5, P1D = 6, P1D_ = 6, P7D = 7, P1W = 7, ...