console
// var c=document.getElementById("myCanvas");
// var ctx=c.getContext("2d");
var img=document.getElementById("tulip");
// ctx.drawImage(img,100, 0, 200, 300);
var canvas = document.createElement('canvas')
var context = canvas.getContext('2d')
const wrap = document.getElementById('wrap')
wrap.appendChild(canvas)
const opts = {
maxWidth: 110,
maxHeight: 250,
scale: 1.5,
}
var pos = calcPosition(img.width, img.height, opts)
canvas.width = pos.w > opts.maxWidth ? opts.maxWidth : pos.w
canvas.height = pos.h > opts.maxHeight ? opts.maxHeight : pos.h
context.drawImage(img, pos.x, pos.y, pos.w, pos.h)
function calcPosition (width, height, opts) {
var isheight = width < height
var scale = isheight ? height / width : width / height
var zoom; var x = 0
var y = 0
var w; var h
var gtScale = function () {
if (isheight) {
zoom = width / 100
w = 100
h = height / zoom
y = (h - opts.maxHeight) / 2
} else {
zoom = height / 100
h = 100
w = width / zoom
x = (w - opts.maxWidth) / 2
}
return {
w: w,
h: h,
x: -x,
y: -y
}
}
var ltScale = function () {
if (isheight) {
zoom = height / opts.maxHeight
h = opts.maxHeight
w = width / zoom
} else {
zoom = width / opts.maxWidth
w = opts.maxWidth
h = height / zoom
}
return {
w: w,
h: h,
x: -x,
y: -y
}
}
return scale > opts.scale ? gtScale() : ltScale()
}
<img id="tulip" src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic01.1sucai.com%2F170320%2F330798-1F32006102389.jpg&refer=http%3A%2F%2Fpic01.1sucai.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1644653179&t=e791c08c6901ee9523d5a7d14a292bd3" alt="The Tulip" />
<br/>
<div id="wrap"></div>