简体   繁体   中英

How to stretch image in canvas?

I need to stretch my image to the top and to the bottom in canvas.

How can I do this ?

Here's the codepen

HTML

<canvas id="myCanvas" width="240" height="297" style="border:1px solid #d3d3d3;">
</canvas>

JS

window.onload = function() {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = new Image;
    img.src = "http://www.w3schools.com/tags/img_the_scream.jpg"
    ctx.drawImage(img, 10, 10);
}

drawImage allows you to pass the width and height as third and fourth parameter. So your last line should be ctx.drawImage(img, 0, 0,c.width, c.height); in order to fill the entire canvas.

Here is a more detailed answer of how to fill or fit a canvas while also keeping the image aspect.

Fill canvas

If you just want an image to stretch to fill in the height you can do something like this jsFiddle : https://jsfiddle.net/CanvasCode/92ekrbnz/

javascript

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = new Image;
ctx.fillStyle = "#000";
ctx.fillRect(0,0,c.width,c.height);
img.src = "http://www.w3schools.com/tags/img_the_scream.jpg"
img.onload = function () {
    ctx.drawImage(img, (c.width / 2) - (img.width / 2), 0, img.width, c.height);
}

However the link you provided basically just zooms into the image. So you can do something like this jsFiddle : https://jsfiddle.net/CanvasCode/92ekrbnz/2/

javascript

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = new Image;

var zoom = 1.0;

img.src = "http://www.w3schools.com/tags/img_the_scream.jpg"

setInterval(function () {
    ctx.fillStyle = "#000";
    ctx.fillRect(0, 0, c.width, c.height);
    ctx.drawImage(img, (c.width / 2) - ((img.width * zoom) / 2), (c.height / 2) - ((img.height * zoom) / 2),
    img.width * zoom,
    img.height * zoom);
}, 1);

document.getElementById("zoomIn").onclick = function () {
    zoom += 0.1;
};
document.getElementById("zoomOut").onclick = function () {
    if (zoom > 0.1) {
        zoom -= 0.1;
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM