Introducing the feature of adding an Opacity Slider specifically designed for the chosen object

I am trying to implement an opacity slider to adjust the visibility of selected objects based on the slider's position (100 indicates complete visibility). I am using fabric.js/master/dist/fabric.js and jQuery 3.3.1. Could you please help me identify what I might be doing wrong in this situation? Find more details about incorporating the Opacity slider on fabricjs.com here.

The error message I encounter is: "Uncaught TypeError: Cannot read property 'opacity' of undefined"

Here is what I currently have: https://codepen.io/s-harper/pen/QxeMXL

Attempts at solutions that I have tried include: Opacity slider for a fabric object

var canvas = new fabric.Canvas("c");
canvas.isDrawingMode = true;

// select, draw
$("#select").click(function() {
  canvas.isDrawingMode = false;
});
$("#draw").click(function() {
  canvas.isDrawingMode = true;
});

var activeObject = canvas.getActiveObject();

$("#alpha").slider( {
       max : 100,
       value : activeObject.opacity * 100,
       slide: function (event, ui) {
           activeObject.setOpacity(ui.value / 100);
           canvas.renderAll();
       },
       stop : function (event, ui) {
           canvas.renderAll();
       }
});
canvas {
  border: solid 1px #000;
}

fieldset {
  max-width: 350px;
}
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c" width="400" height="400"></canvas>
<br>
<button id="draw">Draw</button>
<button id="select">Select</button>
<br>
<br>
<fieldset>
  <legend>Controls</legend>
  <label for="alpha">Opactity</label>
  <input type="range" id="alpha" name="alpha" min="0" max="100" value="100" step="1" />
</fieldset>

Appreciate your assistance!

Answer №1

In order to retrieve the active object, you must utilize events such as selection:created and selection:updated, and employ jQuery UI for implementing a jQuery slider.

DEMO

var canvas = new fabric.Canvas("c");
canvas.isDrawingMode = true;

// toggle between select and draw modes
$("#select").click(function() {
  canvas.isDrawingMode = false;
});
$("#draw").click(function() {
  canvas.isDrawingMode = true;
});
var activeObject = null;
canvas.on('selection:created', function(options) {
  activeObject = options.target;
  $("#alpha").slider("option", "value", activeObject.opacity);
});
canvas.on('selection:updated', function(options) {
  activeObject = options.target;
  $("#alpha").slider("option", "value", activeObject.opacity);
});
canvas.on('selection:cleared', function(options) {
  activeObject = null;
});
$("#alpha").slider({
  max: 1,
  min: 0,
  step: 0.1,
  value: 1,
  slide: function(event, ui) {
    activeObject && (activeObject.opacity = ui.value)
    canvas.requestRenderAll();
  },
  stop: function(event, ui) {
    canvas.requestRenderAll();
  }
});
canvas {
  border: solid 1px #000;
}

fieldset {
  max-width: 350px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<script src="https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c" width="400" height="400"></canvas>
<br>
<button id="draw">Draw</button>
<button id="select">Select</button>
<br>
<br>
<fieldset>
  <legend>Controls</legend>
  <label for="alpha">Opacity</label>
  <div id="alpha" name="alpha"></div>
</fieldset>

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

looping through a linked data object with ng-repeat

I am working with a Node object in my Angular controller. Each Node contains a next property which points to the next item: $scope.Stack = function () { this.top = null; this.rear = null; this.size = 0; this.max_size = 15; ...

How to align two <select> elements side by side using Bootstrap

The issue I am encountering is that these two select elements within the same control-group are being displayed vertically when I want them to be displayed horizontally. I attempted using inline-block in CSS, but there are other <div> elements with ...

Ways to extract a variable from an HTML source using JavaScript and Ajax queries

I'm currently working with Zend Framework 2 and I have a question regarding accessing data defined in HTML within my JavaScript code. Here is the HTML snippet: <tr class="MyClass" data-MyData="<?php echo json_encode($array);?>"> And her ...

I am attempting to implement an auto-assignment feature in my Discord bot using discord.js, however, it seems to be malfunctioning

Trying to implement an autorole feature for my bot following a tutorial, but encountering an error message when testing it on a secondary account in Discord. The section of code related to autorole in my index.js file: client.on("guildMemberAdd" ...

Closing md-tooltip automatically after a specified timeout period

I've set up md-chips in Angular material with the following configuration: <md-chips md-chips-disable-input ng-model="session.participants"> <!-- Chip removal button template --> <button md-chip-remove class ...

AngularJS directive that performs asynchronous validation upon blur

I'm working on developing a directive that validates email addresses provided by users through asynchronous web requests. While the functionality is sound, I've encountered an issue where asynchronous calls are triggered every time a user types a ...

Utilize a Sails.js Single Page Application (SPA) to route all unutilized paths to a centralized controller function

I'm currently working on a project where I am building a single page application (SPA) with Sails.js as the backend. My goal is to have all routes redirect to a single controller action. However, the issue I am facing is that when I try the following ...

The browser is throwing errors because TypeScript is attempting to convert imports to requires during compilation

A dilemma I encountered: <script src="./Snake.js" type="text/javascript"></script> was added to my HTML file. I have a file named Snake.ts which I am compiling to JS using the below configuration: {target: "es6", module: "commonjs"} Howeve ...

Tips for maintaining i18n locale slugs and ensuring i18n consistency when reloading in Next.js

I'm currently utilizing next-translate. The default recognition of my routes is as follows: /about <--- /de/about /es/about However, I would like to set a specific locale for all paths: /en/about <--- /de/about /es/about Below is ...

Phonegap's JavaScript canvas feature is experiencing issues

Recently, I came across a JavaScript bouncing ball animation that works perfectly on the Chrome browser when used on a PC. However, when I tried running it using Phonegap Eclipse Android emulator, I encountered an issue where the canvas appeared blank and ...

``There seems to be an issue with JQuery.Ajax not properly displaying on Samsung Smart

I attempted to use JQuery.Ajax to interact with my webservice Below is the code snippet: Main.onLoad = function() { // Enable key event processing this.enableKeys(); widgetAPI.sendReadyEvent(); //$("#h2Test").html("Change On Text"); ...

Switching the displayed image depending on the JSON data received

As a beginner in javascript and jQuery, I am working on displaying JSON results in the browser. My goal is to generate dynamic HTML by incorporating the JSON data. Below is an example of the JSON structure: [{"JobName":"JobDoSomething","JobStatus":2,"JobS ...

Adjusting the overflow of a parent div based on the position of the div within it by scrolling

I'm trying to create a page with 3 different sections: <div class="container" id="main-container"> <div class="section" id="profile"> Hello World </div> <div class="section" id="projects"> Hello World 2 ...

Steps for transforming an array of objects into an array of values based on a specific key

Is there a way to extract messages based on keywords from a JSON structure? Here is an example of the JSON structure: [{ _id: 123, message: 'hello', username: '1' }, { _id: 456, message: 'world', username: '2'}] I ...

Creating multiple charts with Chart.js in an Angular component is a breeze

Working on an Angular 6 Project, I have a Component that receives a tile Object from its parent. The goal is to generate a Chart using chart.js for each passed tile. The issue is that only the first Chart gets rendered successfully, while the rest fail wit ...

Creating an Eye-Catching Tumblr Landing Page

As I work on Tumblr, my goal is to create a landing page that features an "Enter" button directing users to the home page. After some research, I came across a code snippet that redirects the site to a /welcome page when placed in the index page. <scri ...

Updating values in a mat-select component using the Angular patchValue method

Within my Angular 7 application, I am utilizing the mat-select component from Angular Material in a reactive form. This is how the view appears: <mat-form-field class="col-md-3" color="warn"> <mat-select placeholder="Selectionner la ...

What is the process of calculating the difference between two time values in PHP?

I have searched everywhere online and tried multiple methods over the past couple of days, but still can't seem to achieve the desired result. My goal is to subtract two different times, for example 22:00:00 - 00:30:00 = 21:30:00 $hourToEatLastMeal = ...

Unable to navigate to partial view within MEAN application

I'm currently following a tutorial on creating single page applications using the MEAN stack. So far, I have successfully rendered the index.jade view. However, I encountered an issue when trying to route to a partial view as the DOM of the page does ...

I could use some assistance with implementing a remainder operator by incorporating it into an if statement and outputting the result to

let userInput = prompt('Please enter a number'); let userNumber = parseInt(userInput); let remainder = userNumber % 18; if (userNumber > 18) { console.log('You are old enough to drive!'); } else if (userNumber < 18 && userN ...