在好例子网,分享、交流、成长!
您当前所在位置:首页CSS 开发实例网页布局 → h5网页上传图片

h5网页上传图片

网页布局

下载此实例
  • 开发语言:CSS
  • 实例大小:0.15M
  • 下载次数:7
  • 浏览次数:58
  • 发布时间:2024-11-13
  • 实例类别:网页布局
  • 发 布 人:不忘初
  • 文件格式:.rar
  • 所需积分:1
 相关标签: 上传图片 H5 网页 图片 上传

实例介绍

【实例简介】

h5网页上传图片

【实例截图】

from clipboard

【核心代码】

<style>
.clearfix {clear:both!important}
.tl{text-align:left}
.tc{text-align:center}
.tr{text-align:right}
.fl{float:left}
.fr{float:right}
.c_red {color: red}
.f14{font-size: 14px}
.cursor{cursor:pointer}
</style>
<div class="clearfix" style="position: relative;overflow: hidden;">
    <div class="fl" style="width: 600px;">
    <div style="padding: 16px">
    <div style="background: url('{__static__}/image/bg.png');position: relative;height: 568px;width: 100%">
    <canvas id="canvas" width="568px" height="568px" style="background: #fff;position: relative;z-index: 800">抱歉,您的浏览器不支持canvas元素</canvas>
    <div v-if="is_show == true" style="position: absolute;z-index: 1000;top: 0px;left: 0px;background: rgba(0,0,0,0.5);width: 100%;height: 573px;text-align: center;">
    <div style="margin-top: 230px">
    <!-- element ui 进度条 -->
    <el-progress type="circle" :stroke-width="8" text-color="FFFFFF" :percentage="progress"></el-progress>
    </div>
    </div>
    </div>
    </div>
    </div>
    <div class="fl" style="width: calc(100% - 600px) !important;">
<div class="tc" style="padding-top: 16px;padding-right: 16px;">
    <div class="tl" style="position: relative;width: 100%;height: 183px;cursor: pointer;overflow: hidden;background: url('{__static__}/image/bg.png')">
    <img id="img" src="" @click="showBigImg">
    </div>
    <div style="position: relative !important;width: 100% !important;padding-top: 14px">
    <div>
    <a href="javascript:;" class="loadingfile" style="width: 159px;border-radius: 0px">
选择文件<input type="file" value="" class="head">
</a>
    </div>
    <div class="tl" style="line-height: 32px">
    <span>图片压缩:</span>
    <span>是</span>
    <input type="radio" name="isCs" value="1" />
    <span>否</span>
    <input type="radio" name="isCs" value="2" checked="checked"/>
    </div>
    </div>

</div>
    </div>
</div>
<div class="tpl-botton" style="bottom: 0px;text-align: right;padding-top: 6px;padding-bottom: 2px;padding-right: 6px">

<button type="primary" onclick="onSave()" style="left:10px;" class="mdbtn wabe btn btn-main btn-sm" > 立即上传</button>
  <button style="width:105px" onclick="closeHead()">取消</button>
</div>
<script type="text/javascript">
var form = null;
var imgurl  = "";
var fileData= null;
var imgbase = null;
//var vue = new Vue({
   // el: "#dcappm",
function data() {
        return {
        progress: 0,
        is_show: false,
        }
    }
function created() {
    window.is_show = this.is_show;
    }
   // methods: {
        //保存
function onSave(){
    window.confirm("文件上传");
    var _this = this;
    if(this.is_show){
    window.confirm("文件正在上传中,请稍后操作!");
    //parent.erro("文件正在上传中,请稍后操作!");
    return;
    }
    if(!fileData){
    window.confirm("请上传文件!");
    return;
    }
    if(imgbase == null){
    if(isCheck() == 1){
        initCompression(imgurl, function(){
        upload();
    });
        }else{
        form = new FormData();
                form.append("file", fileData);
                upload();
        }
    }else{
    //组装上传参数
        if(isCheck() == 1){
        initCompression(imgbase, function (){
        upload();
        });
        }else{
        var file = blobToFile(imgbase, fileData.name);
            form = new FormData();
            form.append("file", file);
            upload();
        }
    }
    }
    //上传
function upload(){
    var _this = this;
    this.is_show = true;
    HttpClient({
    //url:  "{__app__}/v1/upload/load", //上传地址
url:  "/upload/", //上传地址
    type: "POST",
    data: form,
    success: function(data){
    _this.progress = 0;
    _this.is_show  = false;
    localStorage.setItem("XFROM_UPLOAD_IMG", JSON.stringify(data.list));
    initView();
    parent.closeformdia(data.msg);
    },
    progress: function(progress){
    _this.progress = Math.ceil(progress);
    },
    error: function(error){
    parent.erro(error);
    }
    });
    }
function showBigImg(val){
    //预览大图,自己实现该功能
    parent.openWord(val.target.currentSrc);
    }
    //}
//});
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
    var context = canvas.getContext('2d');  //2d用单引用括起来
}
//绘制
canvas.drawing = function (x1, y1, x2, y2, e) {
    let self = this;
    if (!context) {
        return;
    } else {
        // 设置画笔的颜色和大小
        context.fillStyle = "red";  // 填充颜色为红色
        context.strokeStyle = "#FF00E4";  // 画笔的颜色
        context.lineWidth = 2;  // 指定描边线的宽度

        context.save();
        context.beginPath();

       if (self.strokeRectFlag) {
            // console.log('画空心矩形')
            self.initCanvas();
            if (e.shiftKey === true) {
                // 正方形
                let d = ((x2 - x1) < (y2 -y1)) ? (x2 - x1) : (y2 - y1);
                context.strokeRect(x1, y1, d, d);
            } else {
                // 普通方形
                context.strokeRect(x1, y1, x2 - x1, y2 - y1);
            }
        } else if (self.strokeCircelFlag) {
            // console.log('画空心圆形')
            self.initCanvas();
            let k = ((x2 - x1) / 0.55);
            let w = (x2 - x1) / 2;
            let h = (y2 - y1) / 2;

            if (e.shiftKey === true) {
                // circle
                let r = Math.sqrt(w * w h * h);
                context.arc(w x1, h y1, r, 0, Math.PI * 2);
            } else {
                // bezier double ellipse algorithm
                context.moveTo(x1, y1 h);
                context.bezierCurveTo(x1, y1 h * 3, x1 w * 11 / 5, y1 h * 3, x1 w * 11 / 5, y1 h);
                context.bezierCurveTo(x1 w * 11 / 5, y1 - h, x1, y1 - h, x1, y1 h);
            }
            context.stroke();
        }
        context.restore();
        context.closePath();
    }
};
//按下鼠标
//canvas.onmousedown = 
function mouseDownAction(e) {
  window.confirm("按下鼠标!");
    let self = this;
    self.X1 = e.offsetX;
    self.Y1 = e.offsetY;
    self.isMouseDown = true;
    //self.loadImage();
};
//移动鼠标
//canvas.onmousemove = 
function mouseMoveAction(e) {
   window.confirm("移动鼠标!");
    let self = this;
    if (self.isMouseDown) {
        self.X2 = e.offsetX;
        self.Y2 = e.offsetY;
        self.drawing(self.X1, self.Y1, self.X2, self.Y2, e);
    }
};

//鼠标抬起
//canvas.onmouseup = 
function mouseUpAction(e) {
   window.confirm("鼠标抬起!");
    let self = this;
    self.lastImage = canvas.toDataURL('image/png');
    self.isMouseDown = false;

    if((e.offsetX - self.X1) > 0 && (e.offsetY - self.Y1) > 0){
    //生成切片图片
    var cvas = document.createElement('canvas')
    var ctt = cvas.getContext('2d');
    var imgs = new Image();
    imgs.crossOrigin = 'Anonymous';
    imgs.src = imgurl;
    imgs.onload = function() {
    //第一次坐标点
    var X1 = self.X1;
    var Y1 = self.Y1;
    //最后坐标点
    var X2 = e.offsetX;
    var Y2 = e.offsetY;

    if(this.width > this.height){
    var pifx = (this.width / canvas.width);
    var newH = (this.height / pifx);
    var tranY = (canvas.height - newH) / 2; //平移点
        //图片上起始真实坐标点
        img_x1  = X1 * pifx;
        img_y1 = (Y1 - tranY) * pifx;
        //图片上最后真实坐标点
        img_x2  = X2 * pifx;
        img_y2 = (Y2 - tranY) * pifx;
//图片的长宽
        var img_w = img_x2 - img_x1;
        var img_h = img_y2 - img_y1;
//绘制图片
cvas.width = img_w;
        cvas.height = img_h;
        ctt.drawImage(imgs, img_x1, img_y1 , img_w , img_h , 0 , 0 , cvas.width , cvas.height);
    }else if(this.width < this.height){
    var pifx = (this.height / canvas.height);
    var newW = (this.width / pifx);
    var tranX = (canvas.width - newW) / 2; //平移点
    //图片上起始真实坐标点
        img_x1  = (X1 - tranX) * pifx;
        img_y1 = Y1 * pifx;
        //图片上最后真实坐标点
        img_x2  = (X2 - tranX) * pifx;
        img_y2 = Y2 * pifx;
//图片的长宽
        var img_w = img_x2 - img_x1;
        var img_h = img_y2 - img_y1;
//绘制图片
cvas.width = img_w;
        cvas.height = img_h;
        ctt.drawImage(imgs, img_x1, img_y1 , img_w , img_h , 0 , 0 , cvas.width , cvas.height);
    }else{
    var pifx = (this.height / canvas.height);
    //图片上起始真实坐标点
        img_x1  = X1 * pifx;
        img_y1 = Y1 * pifx;
        //图片上最后真实坐标点
        img_x2  = X2 * pifx;
        img_y2 = Y2 * pifx;
//图片的长宽
        var img_w = img_x2 - img_x1;
        var img_h = img_y2 - img_y1;
//绘制图片
cvas.width = img_w;
        cvas.height = img_h;
        ctt.drawImage(imgs, img_x1, img_y1 , img_w , img_h , 0 , 0 , cvas.width , cvas.height);
    }
    //显示截图
    var cutImgUrl = cvas.toDataURL('image/png');
    imgbase = cutImgUrl;
    initShows(cutImgUrl);
    }
    }
};
//加载绘制
canvas.loadImage = function () {
   window.confirm("加载绘制!");
    let self = this;
    let img = new Image();
    img.crossOrigin = 'Anonymous';
    img.src = self.lastImage;
    context.drawImage(img, 0, 0, canvas.width, canvas.height);
};
//初始化
canvas.initCanvas = function () {
    context.clearRect(0, 0, canvas.width, canvas.height);
    //canvas.loadImage();
};

//上传请求
var HttpClient = function (param){
var xmlHttp = null;
if (window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}else if (window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if(xmlHttp != null){
if(param.type == null){
window.confirm("请求类型错误");
return;
}
xmlHttp.onload = function() {
    if (this.status == 200) {
      var data = JSON.parse(this.response);
param.success(data);
    };
};
xmlHttp.upload.onprogress = function(e) {
        if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
param.progress(percentComplete);
        }
    };
    xmlHttp.onerror = function(e) {
param.error(e);
    };
//xmlHttp.timeout = 1000*60*20;
xmlHttp.ontimeout = function () {
window.confirm("请求超时");
}
if(param.type == "GET" || param.type == "get"){
xmlHttp.open("GET", param.url, true);//true 异步
}else{
xmlHttp.open("POST", param.url, true);
}
xmlHttp.setRequestHeader('AUTH-TOKEN', localStorage.getItem("xform_token"));
xmlHttp.send(param.data);
}else{
window.confirm("请求不支持");
}
}

//Radio选择值
var isCheck = function (){
var temp = document.getElementsByName("isCs");
var value = 1;
for(var i=0; i < temp.length; i ) {
if(temp[i].checked){
value = temp[i].value;
break;
}
}
return value;
}

//blob流转file
var blobToFile = function (dataurl, fileName){
    var arr = dataurl.split(','),
       mime = arr[0].match(/:(.*?);/)[1],
       bstr = atob(arr[1]),
       n = bstr.length,
       u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    var file = new File([u8arr], fileName, {type: mime});
    file.lastModifiedDate = new Date();
    return file;
};

//图片压缩
var initCompression = function(csImg, success){
   window.confirm("图片压缩!");
var csCanvas = document.createElement('canvas')
    var csContext = csCanvas.getContext('2d');
    var csImage = new Image();
    csImage.crossOrigin = 'Anonymous';
    csImage.src = csImg;
    csImage.onload = function() {
    // 图片原始尺寸
    var originWidth = this.width;
    var originHeight= this.height;
    // 最大尺寸限制
    var maxWidth = 720;
    var maxHeight = 480;
    // 目标尺寸
    var targetWidth = originWidth;
    var targetHeight= originHeight;
    // 图片尺寸超过设置的限制
    if (originWidth > maxWidth || originHeight > maxHeight) {
    if (originWidth / originHeight > maxWidth / maxHeight) {
    targetHeight = maxHeight;
    targetWidth = Math.round(maxHeight * (originWidth / originHeight));
    } else {
    targetWidth = maxWidth;
    targetHeight = Math.round(maxWidth * (originHeight / originWidth));
    }
    }
    //canvas对图片进行缩放
    csCanvas.width = targetWidth;
    csCanvas.height = targetHeight;
    csCanvas.style.background = "rgba(0,0,0,0)";
    // 清除画布
    csContext.clearRect(0, 0, targetWidth, targetHeight);
    // 图片压缩
    csContext.drawImage(csImage, 0, 0, targetWidth, targetHeight);
    var csImgURL     = csCanvas.toDataURL('image/jpeg', 1);
    //组装上传参数
    var file = blobToFile(csImgURL, fileData.name);

    form = new FormData();
    form.append("file", file);

    if(success){
    success();
    }
    }
};

//显示右边小图
var initShows = function(imgurl){
//生成切片图片
    var imgs = new Image();
    imgs.crossOrigin = 'Anonymous';
    imgs.src = imgurl;
    var cut    = document.getElementById("img");
    cut.style   = "";
    var setWH   = 183;
    imgs.onload = function() {
    // 图片原始尺寸
    var originWidth = this.width;
    var originHeight= this.height;
    if(originWidth > originHeight){
    var pifx = (this.width / setWH);
    var newH = (this.height / pifx);
    cut.style.marginTop = (setWH - newH) / 2 "px";
    cut.style.width = "100%";
    }else if(originWidth < originHeight){
    var pifx = (this.height / setWH);
    var newW = (this.width / pifx);
    cut.style.marginLeft= (setWH - newW) / 2 "px";
    cut.style.height = "100%";
    }else{
    cut.style.width = "100%";
    cut.style.height = "100%";
    }
        cut.src    = imgurl;
    }
};

//初始化绘图
var initDraw = function (flag) {
context.globalAlpha = 1;
    canvas.strokeRectFlag = false;
    canvas.strokeCircelFlag = false;
    canvas[flag] = true;
    // 设置鼠标样式,默认画笔,如果
    canvas.style.cursor = "url({__static__}/image/paintbrush.png) 0 0, default";
    if (canvas.eraserFlag) {
        canvas.style.cursor = "url({__static__}/image/eraser-20.png) 10 10, default";
    }
    //添加图片
    canvas.style.background = "url(" imgurl ")";
    canvas.style.backgroundRepeat = "no-repeat";

    var imgs = new Image();
    imgs.crossOrigin = 'Anonymous';
    imgs.src = imgurl;
    imgs.onload = function() {
    if(this.width > this.height){
    var pifx = (this.width / canvas.width);
    var newH = (this.height / pifx);
    canvas.style.backgroundPositionY = (canvas.height - newH) / 2 "px";
    canvas.style.backgroundSize = "100% " newH "px";
    }else if(this.width < this.height){
    var pifx = (this.height / canvas.height);
    var newW = (this.width / pifx);
    canvas.style.backgroundPositionX = (canvas.width - newW) / 2 "px";
    canvas.style.backgroundSize = newW "px 100%";
    }else{
    canvas.style.backgroundSize = "100% 100%";
    }
    }
};

//视频预览
var video = document.createElement('video');
var interval = null;
var initVideo = function(){
context.globalAlpha = 1;
    canvas.style.backgroundRepeat = "no-repeat";
    canvas.style.backgroundSize = "100% 100%";

/* video.setAttribute("controls","controls");
video.setAttribute("autoplay","autoplay");
video.setAttribute("loop","loop");
video.setAttribute("style","width:568px;height:586px"); */

video.controls = false;
video.loop = true;
video.autoplay = true;
video.src    = imgurl;
video.addEventListener('play',function(e){
var width = e.target.videoWidth;
var height = e.target.videoHeight;
//1000/25=40
interval = window.setInterval(function(){
        if(width > height){
        var pifx = (width / canvas.width);
        var newH = (height / pifx);
        var tranH = (canvas.height - newH) / 2
        context.drawImage(video, 0, tranH, canvas.width, newH);
        }else if(width < height){
        var pifx = (height / canvas.height);
        var newW = (width / pifx);
        var tranX = (canvas.width - newW) / 2
        context.drawImage(video, tranX, 0, newW, canvas.height);
        }else{
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        }

        }, 40);
    });
video.addEventListener('pause',function(){
        //clearInterval(interval);
    })
}

//上传音频预览
var audio = new Audio();
var initAudio = function (){
context.globalAlpha = 1;
audio = new Audio();
audio.controls = false;
audio.loop = true;
audio.autoplay = true;
audio.src    = imgurl;

var AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext = new AudioContext();
var analyser = audioContext.createAnalyser();
analyser.fftSize = 256;
analyser = audioContext.createAnalyser();

var audioSrc = audioContext.createMediaElementSource(audio);
audioSrc.connect(analyser);
analyser.connect(audioContext.destination);

context.lineWidth= 2;
var grd = context.createLinearGradient(0, 0, 600, 0);
grd.addColorStop(0, "#30EE20");
grd.addColorStop(1, "#EE2020");

var grd2 = context.createLinearGradient(0, 0, 600, 0);
grd2.addColorStop(0, "#30EE20");
grd2.addColorStop(1, "#EE2020");

var het = 0;
interval = window.setInterval(function(){
context.clearRect(0, 0, canvas.width, canvas.height);
    var dataArray = new Uint8Array(analyser.frequencyBinCount);
    analyser.getByteFrequencyData(dataArray);
    context.beginPath();
    //568px
    for (var i = 0; i < 50; i ) {
        var value = dataArray[6*i];
        context.fillStyle = grd;
        context.fillRect(i * 11.36, 284, 10, -value 1);
        context.fillRect(i * 11.36, 280 - value, 1, het);
        context.fillStyle = grd2;
        context.fillRect(i * 11.36, 284, 10, value 1);
        context.fillRect(i * 11.36, 320 value, 1, het);
    }
    }, 1000 / 60);
}

//其他格式上传预览,可以自己开发
var initOther = function(){
context.globalAlpha = 1;
context.fillStyle = "#ffffff";
context.fillRect(0, 0, canvas.width, canvas.height);
context.font = "30px Arial";
var x = (canvas.width / 2) - 100;
var y = (canvas.height / 2) - 10;

// 创建渐变
var gradient = context.createLinearGradient(0, 0, canvas.width, 0);
gradient.addColorStop("0", "magenta");
gradient.addColorStop("0.5", "blue");
gradient.addColorStop("1.0", "red");

// 用渐变填色
context.strokeStyle = gradient;
context.strokeText("暂 不 支 持 预 览", x, y);
}

//初始化canvas
var initView = function () {
//关闭视频
if(video.playing){
video.pause();
}
if(video){
video.pause();
}
//关闭音频
if(audio){
audio.pause();
}
//清除定时器
for(var n = 0; n <= interval; n ){
clearInterval(n);
}
canvas.style.background = "url('')";
context.globalAlpha = 0;
context.restore();
    //context.closePath();
context.clearRect(0, 0, canvas.width, canvas.height);
}

//关闭
var closeHead = function () {
if(is_show){
parent.erro("图片正在上传中,请稍后操作!");
return;
}
initView();
parent.closeformdia(); //关闭弹出
}

//上传文件
var file = document.querySelector('.head'); //document.getElementById('file');
file.onchange = function() {
    fileData = this.files[0];//这是我们上传的文件
    var reader = new FileReader();
    reader.readAsDataURL(fileData);//异步读取文件内容,结果用data:url的字符串形式表示
    /*当读取操作成功完成时调用*/
    reader.onload = function(e) {
    initView();
    imgurl = this.result;
    var type = fileData.type;
    var suffix = type.split("/");
    if(suffix[0] == "image"){
    initShows(imgurl);
    //方框
            initDraw("strokeRectFlag");
    //圆框
          //initDraw("strokeCircelFlag");
    }else if(suffix[0] == "video"){
    initShows("{__static__}/icon/error2.png");
    //视频
    initVideo();
    }else if(suffix[0] == "audio"){
    initShows("{__static__}/icon/error2.png");
    //音频
    initAudio();
    }else{
    initShows("{__static__}/icon/error2.png");
//其他
    initOther();
    }
    }
}
</script>


实例下载地址

h5网页上传图片

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警