[英]How to stretch image in canvas?
I need to stretch my image to the top and to the bottom in canvas. 我需要将图像延伸到画布的顶部和底部。
HTML HTML
<canvas id="myCanvas" width="240" height="297" style="border:1px solid #d3d3d3;">
</canvas>
JS 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. drawImage允许您将width和height作为第三个和第四个参数传递。 So your last line should be ctx.drawImage(img, 0, 0,c.width, c.height);
因此,您的最后一行应该是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. 这是有关如何填充或适合画布同时又保持图像外观的更详细的答案。
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/ 如果您只想拉伸图像以填充高度,则可以执行以下jsFiddle这样的操作: https ://jsfiddle.net/CanvasCode/92ekrbnz/
javascript 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/ 因此,您可以执行类似jsFiddle的操作: https ://jsfiddle.net/CanvasCode/92ekrbnz/2/
javascript 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;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.