Question

Hi I'm getting image from webcam and I save it on canvas, what I want to do is to stretch it by x and y cooridnates keeping same img dimensions, what I mean is, this is the original webcam picture:

enter image description here

and this is how I wanna it to be when stretched:

enter image description here

<canvas id="canvas" width="640" height="480" style="border:1px solid #d3d3d3;"></canvas>

this is the piece of code that shows source image to <img> element in html , so I have to stretch source image before to show it in html

function snap() {

    if (localMediaStream) {

        ctx.drawImage(video, 0, 0);

        var oImg=document.createElement("img");
        oImg.setAttribute('src', canvas.toDataURL());
        oImg.setAttribute('alt', 'na');
        oImg.setAttribute('width', '1300');
        oImg.setAttribute('height', '1300');
        var img = document.body.appendChild(oImg);
        return img; 
    }

}

any idea on how to stretch the canvas.toDataUrL() source by x and y coordinates and return it stretched to the the src <img> element?

The real problem imo is how to stretch image without altering width and height (as shown via example photos above), is this possible?

Was it helpful?

Solution

You can use the extended properties on context.drawImage that allow scaling/positioning.

enter image description here

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

var img=new Image();
img.onload=function(){
    var w=img.width;
    var h=img.height;
    canvas.width=w;       // set the canvas size to the original image size
    canvas.height=h;
    ctx.drawImage(img,
        0,0,w,h,         // start with the image at original size
        -w/4,0,w*1.25,h  // widen the original image by 1.25X 
                         // and start drawing 1/4th off the left edge of the canvas
    );
}
img.src="temp18.png";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top