最近公司项目一个需求,做海报,图片肯定是要缩放的啦,还不能变形
嗯,就酱,贴出代码吧(●´∀`)ノ♡
逻辑代码
//等比例缩放图片 function changeWidth(imgs, x) { var img = new Image() img.setAttribute("crossOrigin", 'Anonymous');//解决跨域问题 img.onload = function () { var canvas = document.getElementById("tmpCanvas"); var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height);//清空画布,重新画 var imgwidth = img.width; var imgheight = img.height; console.log(imgwidth + " " + imgheight); //得到图片的高宽比,用以计算canvas的高 var scale = imgheight / imgwidth; var cheight = x * scale; ctx.drawImage(img, 0, 0, x, cheight); var image = canvas.toDataURL("image/jpg");//这里返回base64 console.log("====等比例缩放完成===="); console.log(image); console.log("======================"); } img.src = imgs; }
调用
changeWidth("https://www.yangguangdream.com/zb_users/upload/xcx.jpg", 100);
微信扫码查看本文
发表评论