how to draw the select area in the image using canvas

Viewed 450

I need to crop the selected part in the image and I need to draw using canvas enter image description here

if you see in the above image will be 100% width and height in middle of the image there will be one red color border rectangle box will be there I need to draw the visible object inside the rectangle box only using canvas drawImage. how to take the source X & Y and destination X and Y dynamically. this should work when I resize the window also.

I had tried with this code

var imageElm = document.getElementById('image');

var redbox = document.getElementById('box');

var image_height = imageElm .offsetHeight;
var image_width = imageElm .offsetWidth;
var box_width = box.offsetWidth;
var box_height = box.offsetHeight;
var cPoint = document.getElementById('center-point');
var setLeft = cPoint.offsetLeft;
var setTtop = cPoint.offsetTop;
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

context.drawImage(imageElm, setLeft - (box.offsetWidth / 4), setTtop - (box.offsetHeight / 4) , image_width, image_height, 0, 0, image_width, image_height);

<div class="content-row">
        <div class="content">
            <img scr="./images/bg.jpg" id="image" />
            <div id="box" class="border-div">
               <div id="center-point" class="centerPoint"></div>
            </div>
        </div>
        <div class="content">
            <canvas id="canvas"></canvas>
        </div>
    </div>

#image, canvas{
            width: 100%;
            height: calc(100vh - 50px);
            vertical-align: top;
            object-fit: cover;
        }
        
        .content-row{
            display: flex;
            flex-wrap: wrap;
        }
        .content{
            position: relative;
            flex: 0 0 100%;
            max-width: 100%;
        }
        .border-div{
            border: 1px solid red;
            position: absolute;
            width: 100%;
            left:50%;
            top:50%;
            transform: translate(-50%, -50%);
            max-width: 680px;
            height: 300px;
        }
.centerPoint{
            position: absolute;
            left:50%;
            top: 50%;
            width: 15px; height: 15px;
            background-color: rgba(255,255,255, 0.5);
            border-radius: 100px;
            transform: translateX(-50%, -50%);
        }

I added with centre dot point of the screen from that point left and right I tried to draw the selected area in the image that also not working for me.

is there any other solution to achieve this.

out put should be enter image description here

0 Answers
Related