Instructions on relocating a rectangle and capturing its coordinates globally for cropping the chosen image

I am currently a software engineering trainee, focusing on learning Angular CLI. My current project involves image cropping on a canvas, where I draw a circle when clicked.

My query pertains to moving the circle with a mousedown event and stopping it upon mouseup, while also capturing (x, y) coordinates globally to adjust the final cropped image.

Below is the HTML code snippet...

<div class="row">
    <div class="col-sm-6">
    <canvas #layout1 id="layout1" width="500" height="300" 
        (mousedown)="mouseDown($event)" 
        (mouseup)="mouseUp($event)" 
        (mousemove)="coordinates($event)">
        Your browser does not support HTML5 Canvas.
    </canvas>
    </div>
    <div class="col-sm-6">
        <img class="crope-image" src="{{profPic}}" #photo style="width:500px; height:300px;">
    </div>
</div>

Furthermore, here is the TypeScript file...

export class FourComponent implements OnInit {
....some code here...

@ViewChild('layout1') canvas;
@ViewChild('photo') photo;

mouseDown(event: MouseEvent): void {
this.rect.startX = event.pageX - this.offsetLeft;
this.rect.startY = event.pageY - this.offsetTop;
this.drag = true;
const _canvas = this.canvas.nativeElement;
this.event = event;
console.log('kkkk');

this.context.strokeStyle = 'black';
this.context.beginPath();
this.context.arc(this.clientX, this.clientY - 130, 50, 0, 2 * Math.PI);
this.context.stroke();

const _photo = this.photo.nativeElement;
_photo.setAttribute('src', _canvas.toDataURL('image/png'));
this.profPic = _canvas.toDataURL('image/png')

}

mouseUp(event: MouseEvent): void {
this.drag = false;
this.event = event;
}

coordinates(event: MouseEvent): void {
this.clientX = event.clientX;
this.clientY = event.clientY;
this.isMouseDown = event.buttons === 1;
}


ngOnInit() {
const _canvas = this.canvas.nativeElement;
const _photo = this.photo.nativeElement;

this.context = (<HTMLCanvasElement>_canvas).getContext('2d');
this.image = new Image();
this.image.src = '../../assets/images/1.jpg'

this.image.onload = () => {
  this.context.drawImage(this.image, 0, 0, _canvas.width, _canvas.height);
  console.log(this.image.src);
  _photo.setAttribute('src', _canvas.toDataURL('image/png'));
  this.profPic = _canvas.toDataURL('image/png');
 };
 console.log(this.clientX + ',' + this.clientY);
 }
 }

This is my CSS stylesheet...

#layout1{
border:1px solid #d3d3d3;
}
#subcanvas{
border:1px solid #d3d3d3;
}

.crope-image{
border:1px solid #d3d3d3;
}
}

Lastly, here is the current view: https://i.sstatic.net/IVUKC.png

Thank you for your attention...

Answer №1

Learn how to control the movement of a circle by clicking and dragging with your mouse

const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')
canvas.width = canvas.height = 150
let move = false

canvas.addEventListener('mouseup', e => {
    move = false
})
canvas.addEventListener('mousedown', e => {
    move = true
    draw(e)
})
canvas.addEventListener('mousemove', e => {
    draw(e)
})

function draw(e) {
    if (move) {
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      let x = e.clientX - canvas.offsetLeft
      let y = e.clientY - canvas.offsetTop

      ctx.beginPath();
      ctx.arc(x, y, 10, 0, 2 * Math.PI, false);
      ctx.fillText("x=" + x, 10,10);
      ctx.fillText("y=" + y, 10,30);
      ctx.fill();
    }
}
<canvas style="border:1px solid #000000;"></canvas>

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

Exploring the process of updating the background color of a specific component in Angular

I'm currently working on a website that will feature alternating colors of white and black. However, I am facing an issue where I can only apply background color changes globally in the CSS file. Does anyone know how to address this problem? ...

Retrieving a Promise's value for an HTML Element

Hello, I'm new to working with React and JavaScript and could use some assistance. I have a function that returns a Promise that includes an interface. My goal is to access a variable in the interface and use it within <dl><dt>{//string va ...

The dimensions of the box remain fixed and do not change when the screen is resized

Just starting out with HTML and CSS and trying to create a responsive website. Running into an issue where the black striped box on my page is not moving up when I resize the screen. It appears to be stuck in place, causing a gap between it and the slide s ...

mat-stepper each individual stage within the component

My goal is to incorporate a mat-stepper where each step is contained in a separate component. However, I am encountering an issue with preventing the next button from being clicked if the step is not completed: parent.html: <mat-horizontal-stepper> ...

Arranging Div Elements in a Specific Layout

I am currently experimenting with http://jsfiddle.net/ngZdg/ My main goal is to create a parallax website, but I am facing some challenges with the initial layout. I am aiming for the following design: ------------------------------------- | ...

The best location to place a main.scss file within an Angular 2 project

I'm wondering where the best place is to put a main.scss file so that it can be utilized by all components. I attempted to place the css in app.component.ts (root component), but the styles weren't being applied to one of my components. Issue Re ...

Does the Rxjs timer cease functioning when the user switches to a different window?

I have encountered an issue while setting a 60-second countdown with rxjs timer on Angular 11. The countdown works properly as long as the window is kept open. However, if I switch to another tab in the same browser, the timer stops after a few seconds. Th ...

I seem to be having trouble with my dropdown menu, can anyone help me figure out what I might be doing wrong

I'm new to web development and I'm trying to create a dropdown menu. The issue is that when I hover over a specific element, it takes up more space than expected. My goal is for it to appear below the "shop" element. I'm not sure where I&a ...

Is there a way to specifically remove only the last row from a table?

Recently, I encountered a problem with my JS code that adds and removes table rows based on user interaction. Adding rows functioned perfectly, but the issue arose when attempting to delete rows. Instead of deleting only the last row as intended, all rows ...

"Presenting Invoice Information on an Invoice Template: A Step-by-Step Guide

Currently, I am working with Laravel 5.7 and VueJs 2.5.*, where I have a table of invoices. My goal is to create a new component that will display a specific invoice based on user selection, allowing them to view or print the chosen invoice. I am still ex ...

Creating an image dynamically at runtime from a section of HTML code as it appears in the browser

Is there a way to use Java API or Jquery library to create an image from input HTML code? Alternatively, how can I capture a screenshot of a section of HTML code as it appears in the browser? For example: If I have the following HTML code: <h1>Logo& ...

What are the steps to achieve full screen mode in Google Chrome within an Angular 4 Application?

I'm working on an application and I'm looking to incorporate a feature where, when a user navigates from one component to another, the new component's ngOnInit method triggers the Chrome browser to enter full screen mode, similar to pressing ...

Slow auto page refresh in local development for Angular2 on Windows can be quite frustrating

Recently diving into angular2 and following the heros tutorial from docs. Struggling with a sluggish development experience while working with angular2. It's taking approximately 5 seconds for angular2 to recognize changes in files, followed by anothe ...

Is the card-columns class not available in Bootstrap 5.0? Are there any other alternatives provided by Bootstrap besides using CSS media queries and flex column?

While exploring Bootstrap 5.0, I noticed that the card-columns class was missing and there is no mention of it or its alternative in the Bootstrap 5.0 documentation. However, it can still be found in the Bootstrap 4.6 documentation. I understand that usin ...

The outer DIV will envelop and grow taller in conjunction with the inner DIV

Could use a little help here. Thank you :) I'm having trouble figuring out how to get the outer div to wrap around the inner div and expand upwards with the content inside the inner editable div. The inner div should expand from bottom to top, and t ...

Guide on creating dynamic route paths for includes within a Pug template

Need help creating a dynamic include For example: h1 include path/#{object} or include path/+{object}+{a:true,b:11} Something similar to the above. If anyone knows how to achieve this using Mixins in pug, please provide an example for include. ...

"Implementing Python code to dynamically add a class to HTML based on specific conditions

Here is the code snippet I'm currently using for the header section across all templates on my website. I include it in each template using the following line of code: {% include 'header.html' %} I am working on a way to add the class "acti ...

The animation-play-state is set to 'running', however, it refuses to start playing

I'm in the process of creating a landing page that includes CSS animations, such as fade-ins. Initially setting animation-play-state: "paused" in the CSS file, I later use jQuery to trigger the animation while scrolling through the page. While this s ...

Developing a Javascript object using Typescript

Trying my hand at crafting a TypeScript object from JavaScript. The specific JavaScript object I'm attempting to construct can be found here: https://cdnjs.cloudflare.com/ajax/libs/chess.js/0.10.2/chess.js In the provided JavaScript example, the obj ...

Ensure that parameters are validated correctly in the Next.JS application router using the searchParams method

When building the page, I need to properly validate params in the Next.JS app router using searchParams. My goal is to show a main image (coverImage) for each photo on the /gallery page. When a photo is clicked, I want to display more photos of the same k ...