Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 按宽度将图像适配到画布,并将画布适配到图像的新高度_Html_Canvas - Fatal编程技术网

Html 按宽度将图像适配到画布,并将画布适配到图像的新高度

Html 按宽度将图像适配到画布,并将画布适配到图像的新高度,html,canvas,Html,Canvas,如何将画布宽度较大的图像调整到画布(具有比例),然后在按宽度调整后将画布调整到图像高度。 //为画布及其上下文创建一个变量 var canvas=document.getElementById(“imageCanvas”); var ctx=canvas.getContext(“2d”); //初始化图像对象 var image=新图像(); //当它加载图像时 image.onload=函数(){ //获取画布的当前样式 var canvasStyle=getComputedStyle(画布)

如何将画布宽度较大的图像调整到画布(具有比例),然后在按宽度调整后将画布调整到图像高度。

//为画布及其上下文创建一个变量
var canvas=document.getElementById(“imageCanvas”);
var ctx=canvas.getContext(“2d”);
//初始化图像对象
var image=新图像();
//当它加载图像时
image.onload=函数(){
//获取画布的当前样式
var canvasStyle=getComputedStyle(画布);
//得到它的当前宽度,减去末尾的px
var canvasWidth=canvasStyle.width.replace(“px”和“”);
//算出图像比例
var imageRatio=this.width/this.height;
//计算画布的新高度,与图像保持比例
var canvasHeight=canvasWidth/imageRatio;
//将样式标记中画布的高度设置为正确
canvas.style.height=画布高度+“px”;
//将宽度/高度属性设置为正确(因为这是drawImage使用的)
canvas.width=画布宽度;
canvas.height=画布高度;
//以正确的宽度/高度绘制图像
drawImage(这个,0,0,画布宽度,画布高度);
};
//加载图像
image.src=”https://placekitten.com/g/600/800";
#图像画布
{
宽度:400px;
高度:400px;
}