zoukankan      html  css  js  c++  java
  • JavaScript中上传文件为图片如何读取+JS中如何使用clip()剪切指定区域(UI组件之图片剪裁器)

     File读取和FileReader()

    //获取上传的文件/图片
    function getFile(){
        var files,len;
        var reader = new FileReader();
        var img_type;
        addEvent(selectFile,'change',function(){
            files = this.files;//selectFile为上传文件表单,this.files获取选择的文件
            len = files.length;
            if(len > 0){
                img_type = files[0].type;
                if(/image/.test(img_type)){
                    reader.readAsDataURL(files[0]);//读取文件并将文件以数据URL的形式保存在result中
                    var img = new Image();
                    reader.onload = function(){
                        img.src = reader.result;
                        context.drawImage(img,0,0,width,height);
                    }
                }else{
                    console.log('选择的不是图片');
                }
            }else{
    
                alert('未选择文件');
            }
        })
    }

    HTML canvas clip() 方法

    从画布中剪切 200*120 像素的矩形区域。然后,绘制一个红色矩形。只有被剪切区域内的红色矩形部分是可见的:

    实现代码如下:

    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");
    // Clip a rectangular area
    ctx.rect(50,20,200,120);
    ctx.stroke();
    ctx.clip();
    // Draw red rectangle after clip()
    ctx.fillStyle="red";
    ctx.fillRect(0,0,150,100);
    </script>

    clip()这个函数在使用的时候出现问题:

        context.clearRect(0,0,width,height);
       // context.restore();
        context.drawImage(img,0,0,width,height);
       // context.save();
        context.beginPath();
        context.fillStyle = 'rgba(0,0,0,0.3)';
        context.fillRect(0,0,width,height);
        context.fill();
        
    context.beginPath(); context.rect(x_axis,y_axis,clip_width,clip_height); context.lineWidth
    = 3; context.strokeStyle = 'lightblue'; context.stroke(); context.clip(); context.closePath(); context.drawImage(img,0,0,width,height);

    注释掉context.save()和context.restore();后,剪切出现错误,只能在第一次剪切后的区域内进行新的剪切:

    第一次剪切:

    扩大宽度:(没有效果)

    减小宽度:(出现很不想看到的bug)

    context.clearRect(0,0,width,height);
        context.restore();
        context.drawImage(img,0,0,width,height);
        context.save();
        context.beginPath();
        context.fillStyle = 'rgba(0,0,0,0.3)';
        context.fillRect(0,0,width,height);
        context.fill();
        context.beginPath();
        context.rect(x_axis,y_axis,clip_width,clip_height);
        context.lineWidth = 3;
        context.strokeStyle = 'lightblue';
        context.stroke();
        context.clip();
        context.closePath();
    
        context.drawImage(img,0,0,width,height);

    修改后效果正确:

  • 相关阅读:
    React Native 项目常用第三方组件汇总
    react-native-swiper的Github地址
    Navicat for MySQL 使用
    maven项目创7 配置分页插件
    rander()函数执行条件
    RN生命周期
    react-native连接夜神模拟器
    让PHP7达到最高性能的几个Tips
    php安装
    被swoole坑哭的PHP程序员
  • 原文地址:https://www.cnblogs.com/deerfig/p/6764921.html
Copyright © 2011-2022 走看看