javascript 我可以更改画布元素内的图像大小吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22558658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can i change the image size inside a canvas element?
提问by Apostolos
I want to have an image inside a canvas element. The canvas will have static size (e.g 800x600) but the Image
can be larger or smaller. So if the Image is smaller there will be white area round the image, if it is larger the image will not fit the canvas so some parts of the image won't be visible. What i want to ask is the following. Can I resize the image to fit canvas (e.g after user input) after the image has rendered on canvas?
我想在画布元素中有一个图像。画布将具有静态大小(例如 800x600),但Image
可以更大或更小。因此,如果图像较小,图像周围会有白色区域,如果图像较大,图像将不适合画布,因此图像的某些部分将不可见。我想问的是以下内容。图像在画布上呈现后,我可以调整图像大小以适合画布(例如在用户输入之后)吗?
html
html
<canvas id="myCanvas" width="800" height="600">
js
js
canvas = document.getElementById('myCanvas');
context = canvas.getContext('2d');
image = new Image();
image.src = 'url_to_image';
//lets say image is 400x300;
//will this work too?
image.width = image.width*2;
image.height = image.height * 2;
context.drawImage(image, 0, 0);
//or should i use this?
//context.drawImage(image, 0, 0, image.width*2, image.height * 2);
The second one stretches the image to fit the canvas. Can I stretch the image before calling drawImage
(by editing image.width
and image.height
)? I have seen some editing software that zooms on the image and canvas stays static, without changing its size.
第二个拉伸图像以适合画布。我可以在调用之前拉伸图像吗drawImage
(通过编辑image.width
和image.height
)?我见过一些编辑软件可以放大图像并且画布保持静态,而不改变其大小。
回答by
Not correct:
不正确:
image.width = image.width*2;
image.height = image.height * 2;
context.drawImage(image, 0, 0);
as image's width
and height
properties are read-only.
因为图像width
和height
属性是只读的。
Correct:
正确的:
context.drawImage(image, 0, 0, image.width*2, image.height * 2);
Here is another way to make the image fit the canvas independent on aspect ratio:
Simulation background-size: cover in canvas
这是使图像独立于纵横比而适合画布的另一种方法:
Simulation background-size: cover in canvas