Creating a layered image by drawing a shape over a photo in Ionic using canvas

While there are plenty of examples demonstrating how to draw on a canvas, my specific problem involves loading a photo into memory, adding a shape to exact coordinates over the photo, and then drawing/scaling the photo onto a canvas. I'm unsure of where to begin with this task. Are there any libraries compatible with Ionic that can help achieve this?

Edit 1 - Progress update:

Private properties:

@ViewChild('mainCanvas') canvasEl: ElementRef;
private _CANVAS: any;
private _CONTEXT: any;

ionViewDidEnter():

this._CANVAS = this.canvasEl.nativeElement;
this._CONTEXT = this._CANVAS.getContext('2d');

updateCanvas():

var img = new Image();
const ctx = this._CONTEXT;
const canvas = this._CANVAS;

ctx.clearRect(0, 0, this._CANVAS.width, this._CANVAS.height);
ctx.fillStyle = "#ff0000";

img.onload = (() => {
  img.width = img.width;
  img.height = img.height;
  canvas.width = img.width;
  canvas.height = img.height;
  ctx.drawImage(img, 0, 0);
  ctx.lineWidth = 8;
  ctx.strokeStyle = "#FF0000";
  ctx.strokeRect(100, 100, 400, 400);
  ctx.scale(0.5, 0.5); // this does nothing
});

img.src = (<any>window).Ionic.WebView.convertFileSrc(path);

Currently, the code successfully draws the photo and rectangle on the canvas. However, the resulting image is too large for the screen, so I need to scale the canvas after all drawing operations are done. Although I attempted to use ctx.scale, the canvas size remains unchanged regardless of the values I provide.

Answer №1

If you want to add shapes onto a photo, you can't directly draw on the photo itself. However, you can create a separate canvas offscreen that matches the size of the photo, draw the photo onto it, and then draw your shapes on top of it.

After adding your shapes, you can display the combined result on your main canvas.

// Example with an empty image
const img = new Image(100, 100);

// Create a new canvas for demonstration
const mainCanvas = document.createElement('canvas');
const mainCtx = mainCanvas.getContext('2d');

// Creating an offscreen buffer canvas
const bufferCanvas = document.createElement('canvas');
const bufferCtx = bufferCanvas.getContext('2d');

// Adjust size of buffer canvas to match image
bufferCanvas.width = img.width;
bufferCanvas.height = img.height;

if (bufferCtx && mainCtx) {
  // Draw the image onto buffer canvas
  bufferCtx.drawImage(img, 0, 0);
  // Add a rectangle in the center of the image
  bufferCtx.fillRect(img.width / 2 - 5, img.height / 2 - 5, 10, 10);

  // Display the buffer on the main canvas
  mainCtx.drawImage(bufferCanvas, 0, 0);
}

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

Troubleshooting: Vue.js custom select element not responding to blur event

Unique Scenario A custom autocomplete select component has been created that not only autocompletes but also allows for adding a new value if the result is not found. This functionality was discovered to be missing in the vue-select module. Explore the C ...

Utilizing Node Js and Selenium webdriver, what is the process of dragging and dropping an element from its current position to a new position just below it?

After multiple attempts, I have come to realize that the following code is ineffective. driver.findElement(By.xpath(xpath)).then(function (element1) { driver.findElement(By.xpath(xpath)).then(function (element2) { ...

Is there a way for me to determine when a user has signed in for the first time?

Issue at Hand I am facing an obstacle in detecting when a user initially connects to Google on my app using Firebase. The method I am currently utilizing is auth.signInWithPopup(googleProvider);. To address this query, I delved into the documentation and ...

jquery method for retrieving default value from dropdown list

When no option is selected from the dropdown list, I require the default value to be used for business logic purposes. ...

Utilizing Zend JSON encoding for seamless integration with JavaScript

I'm currently working with the Zend Framework. My objective is to pass JSON data from the controller to JavaScript. I have a simple array: $array = array('a' => 1, 'b' => 2); After encoding this array into JSON format: ...

Tracking a user's path while redirecting them through various pages

Recently, I created a website with a login page and a home page using nodejs, javascript, and html. The client side sends the entered username and password to the server, which then replies based on the validation result. During navigation between pages, h ...

Executing all middleware within an express route

Currently, I am in the process of constructing an API using express and have implemented multiple middleware functions in my routes. One of the endpoints I am working on is displayed below: Router.route('/:id/documents') .get([isAuthenticated, ...

Trouble with minified scripts on a particular server

Apologies if this has already been addressed, but I've been searching for a solution for hours. I created a basic website that works perfectly on my own hosting. However, when I transfer it to new hosting (same company, same package, different server ...

In JavaScript, filter out an array of image links that end with .jpg, .jpeg, .png, or

Need assistance, could someone lend a hand? I've got an array of image URLs and I'm attempting to filter out only the links with supported images using regex or endsWith(). It's been a struggle all morning. Appreciate any help offered! ...

Issue occurs when a circle element is not following a div element on mouse

Currently, I have implemented some jQuery code that instructs a div named small-circle to track my cursor movement. I discovered how to accomplish this by referencing a thread on stack overflow. I made slight modifications to the script to suit my specifi ...

Show PHP results in an Ajax modal box

Hey everyone! I'm new to this and had some code written for me by a programmer. Unfortunately, I can't reach out to them for help anymore. I have a calculator that shows results (generated by calc.php) without refreshing the page. Check out the ...

When using node.js express, the req.body object does not yield any results

My web server setup with express appears to be functioning correctly, however, I am encountering an issue where the req.body returns nothing. Despite not receiving any errors, the console.log(req.body) doesn't show anything in the console output. Stra ...

It is not possible to include external JavaScript in a Vue.js web page

Trying to integrate a Google Translate widget onto my webpage has been a bit challenging. Initially, when I added it to a normal webpage, it worked smoothly using the following code: <div class="google_translate" id="google_translate_element"></d ...

Encountered an unexpected forward slash while trying to parse JSON using

When passing a file, why does the `parseJSON` function fail? The file is stored in variable a and then I attempt to parse it using `parseJSON`. var a = "/android/contents/img/uploads/img_2A0.png"; var result = jQuery.parseJSON(a); The error being displa ...

Connecting a dynamically assessed function on the $scope to a service

Within my code, there is a function called make_value_summary that has the capability to generate a generic summary of various fields within the $scope. By applying this function, I am able to create location_summary, which is then linked to the view using ...

Tips for using jQuery to add several image source URLs to an array

My JavaScript code uses jQuery to collect all image sources on document load and store them in an array: var sliderImg = []; sliderImg.push($('.thumbnail').children('img').attr('src')); Then, I have a click event set up to a ...

What is the best way to transfer data from a div tag to an li tag using JavaScript?

https://i.stack.imgur.com/se2qk.pngI am attempting to change the div tag content to li tag. Here is a snippet of the code from inspect for reference. I need to remove the div tag with the "domTitle" class. <li style="display: inline;" id="list_name"> ...

Navigating between routes in NEXT JS involves passing state, which can be achieved through various

Within one of my page objects, I have some data that I need to send to another page when redirecting. The code snippet below shows how I achieved this: const redirectAppointmentStep1 = (value) => { router.push({ pathname: '/Appointment/bo ...

Access a JSON value in the Google Sheets script editor and retrieve the data

I'm trying to retrieve a value from a JSON object by making an API call in a Google Sheet. Below is the script I am using: function getBitcoinPrice() { var url = "https://acx.io//api/v2/tickers/btcaud.json"; var response = UrlFetchApp.fetc ...

Leveraging electron-usb alongside electron

I attempted to integrate the electron-usb library into my electron project. Upon running npm start with require('electron-usb') in my index.html file, an error is displayed in the console: Uncaught Error: The specified procedure could not be fo ...