javascript使用canvas画布调整图片大小

所属分类: 网页特效-图片特效&上传    2023-12-19 10:53:40

javascript使用canvas画布调整图片大小 ie兼容6
反馈问题  查看演示  登录后下载 温馨提示
登录会员即可享受免费下载
 我要建站

javascript使用canvas画布调整图片大小(共3个文件)

    • index.html

使用方法

//resize and draw the image on first load
resizeImage(imagePath, 360, 240);

//resize the image and draw it to the canvas
function resizeImage(imagePath, newWidth, newHeight) {
    //create an image object from the path
    const originalImage = new Image();
    originalImage.src = imagePath;
 
    //get a reference to the canvas
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
 
    //wait for the image to load
    originalImage.addEventListener('load', function() {
        
        //get the original image size and aspect ratio
        const originalWidth = originalImage.naturalWidth;
        const originalHeight = originalImage.naturalHeight;
        const aspectRatio = originalWidth/originalHeight;
 
        //if the new height wasn't specified, use the width and the original aspect ratio
        if (newHeight === undefined) {
            //calculate the new height
            newHeight = newWidth/aspectRatio;
            newHeight = Math.floor(newHeight);
            
            //update the input element with the new height
            hInput.placeholder = `Height (${newHeight})`;
            hInput.value = newHeight;
        }
      
        //set the canvas size
        canvas.width = newWidth;
        canvas.height = newHeight;
         
        //render the image
        ctx.drawImage(originalImage, 0, 0, newWidth, newHeight);
    });
}

const downloadBtn = document.querySelector("button.download");
 
//a click event handler for the download button
//download the resized image to the client computer
downloadBtn.addEventListener('click', function() {
    //create a temporary link for the download item
    let tempLink = document.createElement('a');

    //generate a new filename
    let fileName = `kuli8.jpg`;
  
    //configure the link to download the resized image
    tempLink.download = fileName;
    tempLink.href = document.getElementById('canvas').toDataURL("image/jpeg", 0.9);
  
    //trigger a click on the link to start the download
    tempLink.click();
});

站长提示:
1. 平台上所有素材资源,需注册登录会员方能正常下载。
2. 会员用户积极反馈网站、素材资源BUG或错误问题,每次奖励20K币
3. PHP源码类素材,如需协助安装调试,或你有二次开发需求,可联系苦力吧客服。
4. 付费素材资源,需充值后方能下载,如有任何疑问可直接联系苦力吧客服
相关资源 / 图片特效&上传

纯js自动切换图片滑块特效代码

一款图片自动切换特效,集成了自动切换图片,每隔3秒钟自动滑动切换到下一张图片。
  图片特效&上传
 206  

jquery可关闭的横幅广告图片自动切换插件

一款横幅图片自动切换插件,图片可自定义到脚本数组里,自动触发切换图片。
  图片特效&上传
 197  

jquery支持自定义的手机端图片上传插件

可自定义设置上传图片数量、图片格式、图片大小等,带上传本地预览,使用input原生事件配合接口实现图片上传。
  图片特效&上传
 303  

原生js图片反向动画拆分滚动效果

一款很有趣的图片滚动特效,拉动滚动条上下两组图片反方向拆分。
  图片特效&上传
 210  

评论数(0) 回复有机会获得K币 用户协议

^_^ 还没有人评论,快来抢个沙发!
😀
  • 😀
  • 😊
  • 😂
  • 😍
  • 😑
  • 😷
  • 😵
  • 😛
  • 😣
  • 😱
  • 😋
  • 😎
  • 😵
  • 😕
  • 😶
  • 😚
  • 😜
  • 😭
发表评论