JavaScript中上传文件为图片如何读取+JS中如何使用clip()剪切指定区域(UI组件之图片剪裁器)  File读取和FileReader() HTML canvas clip() 方法

//获取上传的文件/图片
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 像素的矩形区域。然后,绘制一个红色矩形。只有被剪切区域内的红色矩形部分是可见的:

JavaScript中上传文件为图片如何读取+JS中如何使用clip()剪切指定区域(UI组件之图片剪裁器)
 File读取和FileReader()
HTML canvas clip() 方法

实现代码如下:

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();后,剪切出现错误,只能在第一次剪切后的区域内进行新的剪切:

第一次剪切:

JavaScript中上传文件为图片如何读取+JS中如何使用clip()剪切指定区域(UI组件之图片剪裁器)
 File读取和FileReader()
HTML canvas clip() 方法

扩大宽度:(没有效果)

JavaScript中上传文件为图片如何读取+JS中如何使用clip()剪切指定区域(UI组件之图片剪裁器)
 File读取和FileReader()
HTML canvas clip() 方法

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

JavaScript中上传文件为图片如何读取+JS中如何使用clip()剪切指定区域(UI组件之图片剪裁器)
 File读取和FileReader()
HTML canvas 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);

修改后效果正确:

JavaScript中上传文件为图片如何读取+JS中如何使用clip()剪切指定区域(UI组件之图片剪裁器)
 File读取和FileReader()
HTML canvas clip() 方法

JavaScript中上传文件为图片如何读取+JS中如何使用clip()剪切指定区域(UI组件之图片剪裁器)
 File读取和FileReader()
HTML canvas clip() 方法