Not save the image portion with the exact selected area

19 Views Asked by At

see the image i require that selected yellow part as image but it save extra approx 10px right part

Using the below code, I try save image areas by selection with the mouse, but when I save the image and open it to see whether the selected portion is exact or not, it does not match a little bit.please guide me that how to i save exact portion of image part. i already done saving part in my folder and database but issue is its not save right portion means not match exact may be some issue related to coords during selection.

` Save Selected Areas

<script>
    jQuery(document).ready(function () {
        var selectedAreas = [];
        var deselectModeActive = false;

        var canvas = document.getElementById('selectableCanvas');
        var ctx = canvas.getContext('2d');

        var image = new Image();
        image.src = jQuery('#selectableImage').attr('src');

        image.onload = function () {
            ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
        };

        canvas.addEventListener('mousedown', handleMouseDown);
           function handleMouseDown(e) {
            var startX = e.clientX - canvas.getBoundingClientRect().left;
            var startY = e.clientY - canvas.getBoundingClientRect().top;

            var area = {
                startX: startX,
                startY: startY,
                points: [{ x: startX, y: startY }],
            };
            canvas.addEventListener('mousemove', handleMouseMove);
               function handleMouseMove(e) {
                var x = e.clientX - canvas.getBoundingClientRect().left;
                var y = e.clientY - canvas.getBoundingClientRect().top;

                // Clear the canvas and redraw the image
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(image, 0, 0, canvas.width, canvas.height);

                // Draw all previously selected areas
                for (var i = 0; i < selectedAreas.length; i++) {
                    drawSelection(selectedAreas[i].points);
                }
                // Draw the selection area
                area.points.push({ x: x, y: y });
                drawSelection(area.points);
            }

            canvas.addEventListener('mouseup', function handleMouseUp() {
                canvas.removeEventListener('mousemove', handleMouseMove);
                canvas.removeEventListener('mouseup', handleMouseUp);

                // Draw the final selection area
                drawSelection(area.points);

                // Store the selected area
                selectedAreas.push(area);

                console.log('Selected areas:', selectedAreas);
            });
        }

        function drawSelection(points) {
            ctx.beginPath();
            ctx.moveTo(points[0].x, points[0].y);

            for (var i = 1; i < points.length; i++) {
                ctx.lineTo(points[i].x, points[i].y);
            }

            ctx.closePath();
            ctx.strokeStyle = 'yellow';
            ctx.lineWidth = 2;
            ctx.stroke();
            ctx.fillStyle = 'rgba(255, 255, 0, 0.3)';
            ctx.fill();
        }

        jQuery('#saveAreas').on('click', function () {
            // Send the selected areas to the server (Ajax code remains the same)
            if (selectedAreas.length === 0) {
                alert('No areas selected!');
                return;
            }

            var dataToSend = [];
            var mainImage = jQuery('#selectableImage').attr('src').split('/').pop();

            for (var i = 0; i < selectedAreas.length; i++) {
                var area = selectedAreas[i];

                // Create a new canvas for each selected area
                // var areaCanvas = document.createElement('canvas');
                // var areaCtx = areaCanvas.getContext('2d');

                // Calculate the bounding box of the selected area
                var minX = Math.min.apply(null, area.points.map(point => point.x));
                var minY = Math.min.apply(null, area.points.map(point => point.y));
                var maxX = Math.max.apply(null, area.points.map(point => point.x));
                var maxY = Math.max.apply(null, area.points.map(point => point.y));
                // Create a new canvas for each selected area
                var areaCanvas = document.createElement('canvas');
                var areaCtx = areaCanvas.getContext('2d');
                // Set canvas dimensions to match the bounding box
                areaCanvas.width = maxX - minX;
                areaCanvas.height = maxY - minY;

                // Draw the selected area on the canvas
                areaCtx.beginPath();
                areaCtx.moveTo(area.points[0].x - minX, area.points[0].y - minY);

                for (var j = 1; j < area.points.length; j++) {
                    areaCtx.lineTo(area.points[j].x - minX, area.points[j].y - minY);
                }

                areaCtx.closePath();
                areaCtx.fillStyle = 'rgba(255, 255, 255, 1)';
                areaCtx.fill();
                areaCtx.globalCompositeOperation = 'source-in';
                areaCtx.drawImage(image,
                minX,
                minY, 
                areaCanvas.width,
                areaCanvas.height, 
                0, 0,         
                areaCanvas.width,
                areaCanvas.height);

                // Convert canvas content to base64 string
                var base64String = areaCanvas.toDataURL('image/png');

                // Store base64 string and area information in an object
                var areaData = {
                    base64String: base64String,
                    area: {
                        points: area.points,
                    },
                    mainImg: mainImage
                };

                // Push the object to the data array
                dataToSend.push(areaData);
            }

            // Send all base64 strings and area information to the server
            jQuery.ajax({
                type: 'POST',
                url: 'http://localhost/snap-news/save.php',
                contentType: 'application/json', // Set content type to JSON
                data: JSON.stringify({ areas: dataToSend }), // Convert data to JSON string
                success: function (response) {
                    console.log(response);
                    alert('Selected areas saved successfully!');
                },
                error: function (error) {
                    console.error(error);
                    alert('Error saving selected areas!');
                }
            });
        });

    });
</script>`

please guide me to how i save exact portion from main image.

0

There are 0 best solutions below