console
let videoWidth = 90
let viedeoHeight = 64
let cWidth
let cHeight
let canvas = document.getElementById('canvas')
let ctx = canvas.getContext('2d')
let img = document.getElementById('a')
let canvas2 = document.getElementById('canvas2')
let ctx2 = canvas2.getContext('2d')
let canvas3 = document.getElementById('canvas3')
let ctx3 = canvas3.getContext('2d')
function getRect(){
let sty = canvas.getBoundingClientRect()
cWidth = sty.width
cHeight = sty.height
canvas.width = cWidth
canvas.height = cHeight
canvas2.width = cWidth
canvas2.height = cHeight
canvas3.width = cWidth
canvas3.height = cHeight
}
function setArea(){
// 1.
if((cWidth/cHeight) >= (videoWidth/viedeoHeight)){
let width = videoWidth*cHeight/viedeoHeight
// 偏长
ctx.drawImage(img,cWidth > width ? (cWidth-width)/2 : 0,0,width,cHeight )
} else {
let height = viedeoHeight*cWidth/videoWidth
// 偏高
ctx.drawImage(img,0,cHeight > height ? (cHeight-height)/2 : 0,cWidth,height )
}
// 2.
ctx2.drawImage(img,0,0,cWidth,cHeight)
// 3.
if((cWidth/cHeight) >= (videoWidth/viedeoHeight)){
let height = viedeoHeight*cWidth/videoWidth
// 偏长
ctx3.drawImage(img,0,height > cHeight ? -(height-cHeight)/2 : 0,cWidth,height )
} else {
let width = videoWidth*cHeight/viedeoHeight
// 偏高
ctx3.drawImage(img,width > cWidth ? -(width-cWidth)/2 : 0,0,width,cHeight )
}
}
getRect()
setArea()
new ResizeObserver(()=>{
getRect()
setArea()
}).observe(document.getElementById('txt'))
<h1>用canvas渲染图片/视频的比例处理</h1>
<img src="https://cdns.jsrun.net/css/img/logo@2x.png" alt="" id="a">
<h2>保持比例,不裁剪</h2>
<p>通过拖拉第一个框的右下角来改变大小</p>
<div id="con">
<canvas id="canvas"></canvas>
<textarea name="txt" id="txt" cols="30" rows="10"></textarea>
</div>
<h2>占满容器,不裁剪</h2>
<canvas id="canvas2"></canvas>
<h3>占满容器,保持比例,裁剪</h3>
<canvas id="canvas3"></canvas>
img{
width: 1px;
height: 1px;
}
canvas{
background: #000;
}
#con canvas{
width: calc(100% - 5px);
height: calc(100% - 8px);
position: absolute;
left: 0;
top: 0;
z-index: 1;
}
#con {
position: relative;
width: auto;
float: left;
}
#con textarea{
width: 90px;
height: 64px;
resize: both;
}
h2{
clear: both;
}