Apo*_*los 3 javascript html5 canvas image
我想在canvas元素内有一个图像。画布将具有静态尺寸(例如800x600),但Image可以更大或更小。因此,如果图像较小,则图像周围会有白色区域;如果图像较大,则图像将不适合画布,因此图像的某些部分将不可见。我想问的是以下内容。图像在画布上渲染后,是否可以调整图像大小以适合画布(例如在用户输入之后)?
html
<canvas id="myCanvas" width="800" height="600">
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
第二个拉伸图像以适合画布。我可以在调用之前拉伸图像drawImage(通过编辑image.width和image.height)吗?我看过一些编辑软件,它可以放大图像,并且画布保持静态,而不会更改其大小。
小智 7
不正确:
image.width = image.width*2;
image.height = image.height * 2;
context.drawImage(image, 0, 0);
Run Code Online (Sandbox Code Playgroud)
因为image width和heightproperties是只读的。
正确:
context.drawImage(image, 0, 0, image.width*2, image.height * 2);
Run Code Online (Sandbox Code Playgroud)
这是使图像适合画布而不依赖于宽高比的另一种方法:
模拟背景大小:画布中的封面