我想在 Canvas 元素内放置一个图像。 Canvas 将具有静态尺寸(例如 800x600),但Image
可以更大或更小。因此,如果图像较小,图像周围会有白色区域,如果图像较大,则图像将不适合 Canvas ,因此图像的某些部分将不可见。我想问的是以下内容。图像在 Canvas 上渲染后,我可以调整图像大小以适合 Canvas (例如,在用户输入之后)吗?
html
<canvas id="myCanvas" width="800" height="600">
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);
第二个拉伸(stretch)图像以适合 Canvas 。我可以在调用drawImage
之前拉伸(stretch)图像(通过编辑image.width
和image.height
)吗?我见过一些编辑软件可以放大图像,而 Canvas 保持静态,而不改变其大小。
最佳答案
不正确:
image.width = image.width*2;
image.height = image.height * 2;
context.drawImage(image, 0, 0);
因为图像的 width
和 height
属性是只读。
正确:
context.drawImage(image, 0, 0, image.width*2, image.height * 2);
这是另一种使图像适合 Canvas 且与宽高比无关的方法:
Simulation background-size: cover in canvas
关于javascript - 我可以更改 Canvas 元素内的图像大小吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22558658/