<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="format-detection" content="telephone=yes">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>weapp ui</title>
</head>
<body>
<p>要使用的图像:</p>
<img id="aimImg" src="https://res.wx.qq.com/mpres/zh_CN/htmledition/pages/login/loginpage/images/bg_banner49d02a.png" alt="aimImg" />
<p>画布:</p>
<canvas id="myCanvas" width="320" height="180" style="border:1px solid #d3d3d3;background:#ffffff;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var img=document.getElementById('aimImg');
img.onload = function () {
var ctx = document.getElementById('myCanvas').getContext('2d');
console.log(img.width, img.height, c.width, c.height);
// 计算出 图片距离左上角的距离 和图片的大小 canvans按照 宽高比16:9布局
var w = c.width, h = img.height * c.width/img.width, cw = 0, ch = (c.height - h) / 2;
if (img.width*9/16 < img.height) {
w = img.width * c.height / img.height; h = c.height; cw = (c.width - w) / 2; ch = 0;
}
ctx.drawImage(img, cw, ch, w, h);
}
</script>
</body>
</html>
H5画板如何将图片自适应画在里面
最新推荐文章于 2022-12-19 16:48:35 发布