weixin_46423206 2020-07-25 20:41 采纳率: 0%
浏览 68

如何上传图片在画布上

图片说明
想将图片点击上传到画布里(canvas(背景)),并且可以描画,在网上查了半天也没弄明白,希望那位大佬教教,

HTML
<!doctype html>
<html lang="zh-cmn-Hans">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title></title>

    <link rel="stylesheet" href="//at.alicdn.com/t/font_584725_0nyjbeaxjw2ep14i.css">
    <link rel="stylesheet" href="css/style.css">
</style> 
</head>
<body>

    <canvas id="drawing-board" width="500" height="500">
</canvas>

 </div> 
    <div class="color-group">
        <ul>
            <li id="black" class="color-item active" style="background-color: black;"></li>
            <li id="red" class="color-item" style="background-color: #FF3333;"></li>
            <li id="blue" class="color-item" style="background-color: #0066FF;"></li>
            <li id="yellow" class="color-item" style="background-color: #FFFF33;"></li>
            <li id="green" class="color-item" style="background-color: #33CC66;"></li>
            <li id="gray" class="color-item" style="background-color: gray;"></li>
            <li id="fuchsia" class="color-item" style="background-color: fuchsia;"></li>
            <li id="aqua" class="color-item" style="background-color: aqua;"></li>
            <li id="purple" class="color-item" style="background-color: purple;"></li>
            <li id="maroon" class="color-item" style="background-color: maroon;"></li>



        </ul>
    </div>
    <div id="range-wrap"><input type="range" id="range" min="1" max="8" value="5" title=""></div>
    <div class="tools">
        <button id="brush" class="active" title=""><i class="iconfont icon-qianbi">笔</i></button>
        <button id="eraser" title="" text=""><i class="iconfont icon-xiangpi">橡皮</i></button>
        <button id="clear" title=""><i class="iconfont icon-qingchu">清除</i></button>
        <button id="undo" title=""><i class="iconfont icon-chexiao">返回</i></button>
        <button id="save" title=""><i class="iconfont icon-fuzhi">保存</i></button>
 <input type='button' for="file"  class="file1" value="上传图片" />  
  <input type="file"  class="file" id="upload" />     
      <div id="result">
      </div>

   </div>
</body>
<script src="js/main.js"></script>
</html>




JS


  let canvas = document.getElementById("drawing-board");
    let ctx = canvas.getContext("2d");
    let eraser = document.getElementById("eraser");
    let brush = document.getElementById("brush");
    let reSetCanvas = document.getElementById("clear");
    let aColorBtn = document.getElementsByClassName("color-item");
    let save = document.getElementById("save");
    let undo = document.getElementById("undo");
    let range = document.getElementById("range");
    let clear = false;
    let activeColor = 'black';
    let lWidth = 4;


    let offsetLeft = canvas.getBoundingClientRect().left
    let offsetTop = canvas.getBoundingClientRect().top


    autoSetSize(canvas);

    setCanvasBg('white');

    listenToUser(canvas);

    getColor();


    function showImg(){
            // var img_file =  $("#img_file").val();
            var file =  document.getElementById('img_file').files[0];
            var re = new FileReader();
            re.readAsDataURL(file);
            re.onload = function(re){
                $('#img_id').attr("src", re.target.result);
            }
        }


    window.onbeforeunload = function () {
        return "Reload site?";
    };

    function autoSetSize(canvas) {
        canvasSetSize();

        function canvasSetSize() {
            let pageWidth = document.documentElement.clientWidth;
            let pageHeight = document.documentElement.clientHeight;

            canvas.width = 500;
            canvas.height = 500;
        }

        window.onresize = function () {
            canvasSetSize();
        }
    }

    function setCanvasBg(color) {
        ctx.fillStyle = color;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = "black";
    }

    function listenToUser(canvas) {
        let painting = false;
        let lastPoint = { x: undefined, y: undefined };

        if (document.body.ontouchstart !== undefined) {
            canvas.ontouchstart = function (e) {
                let x = e.touches[0].clientX;
                let y = e.touches[0].clientY;
                this.firstDot = ctx.getImageData(0, 0, canvas.width, canvas.height);
                saveData(this.firstDot);
                painting = true;

                lastPoint = { "x": x, "y": y };
                ctx.save();
                drawCircle(x - offsetLeft, y - offsetTop, 0);
            };
            canvas.ontouchmove = function (e) {
                if (painting) {
                    let x = e.touches[0].clientX;
                    let y = e.touches[0].clientY;
                    let newPoint = { "x": x, "y": y };
                    drawLine(lastPoint.x - offsetLeft, lastPoint.y - offsetTop, newPoint.x - offsetLeft, newPoint.y - offsetTop, clear);
                    lastPoint = newPoint;
                }
            };

            canvas.ontouchend = function () {
                painting = false;
            }
        } else {
            canvas.onmousedown = function (e) {
                this.firstDot = ctx.getImageData(0, 0, canvas.width, canvas.height);
                saveData(this.firstDot);
                painting = true;
                let x = e.clientX;
                let y = e.clientY;
                lastPoint = { "x": x, "y": y };
                ctx.save();
                drawCircle(x - offsetLeft, y - offsetTop, 0);
            };
            canvas.onmousemove = function (e) {
                if (painting) {
                    let x = e.clientX;
                    let y = e.clientY;
                    let newPoint = { "x": x, "y": y };
                    drawLine(lastPoint.x - offsetLeft, lastPoint.y - offsetTop, newPoint.x - offsetLeft, newPoint.y - offsetTop, clear);
                    lastPoint = newPoint;
                }
            };

            canvas.onmouseup = function () {
                painting = false;
            };

            canvas.mouseleave = function () {
                painting = false;
            }
        }
    }

    function drawCircle(x, y, radius) {
        ctx.save();
        ctx.beginPath();
        ctx.arc(x, y, radius, 0, Math.PI * 2);
        ctx.fill();
        if (clear) {
            ctx.clip();
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.restore();
        }
    }

    function drawLine(x1, y1, x2, y2) {
        ctx.lineWidth = lWidth;
        ctx.lineCap = "round";
        ctx.lineJoin = "round";
        if (clear) {
            ctx.save();
            ctx.globalCompositeOperation = "destination-out";
            ctx.moveTo(x1, y1);
            ctx.lineTo(x2, y2);
            ctx.stroke();
            ctx.closePath();
            ctx.clip();
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.restore();
        } else {
            ctx.moveTo(x1, y1);
            ctx.lineTo(x2, y2);
            ctx.stroke();
            ctx.closePath();
        }
    }

    range.onchange = function () {
        lWidth = this.value;
    };

    eraser.onclick = function () {
        clear = true;
        this.classList.add("active");
        brush.classList.remove("active");
    };

    brush.onclick = function () {
        clear = false;
        this.classList.add("active");
        eraser.classList.remove("active");
    };

    reSetCanvas.onclick = function () {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        setCanvasBg('white');
    };

    save.onclick = function () {
        let imgUrl = canvas.toDataURL("image/png");
        let saveA = document.createElement("a");
        document.body.appendChild(saveA);
        saveA.href = imgUrl;
        saveA.download = "zspic" + (new Date).getTime();
        saveA.target = "_blank";
        saveA.click();
    };

    function getColor() {
        for (let i = 0; i < aColorBtn.length; i++) {
            aColorBtn[i].onclick = function () {
                for (let i = 0; i < aColorBtn.length; i++) {
                    aColorBtn[i].classList.remove("active");
                    this.classList.add("active");
                    activeColor = this.style.backgroundColor;
                    ctx.fillStyle = activeColor;
                    ctx.strokeStyle = activeColor;
                }
            }
        }
    }

    let historyDeta = [];

    function saveData(data) {
        (historyDeta.length === 10) && (historyDeta.shift());
        historyDeta.push(data);
    }

    undo.onclick = function () {
        if (historyDeta.length < 1) return false;
        ctx.putImageData(historyDeta[historyDeta.length - 1], 0, 0);
        historyDeta.pop()
    };



CSS

.line { position:relative; float:left; padding:8px 0}  
.line span { float:left}  
input { border:1px solid #888; vertical-align:middle}  
.file { position:absolute; left:90px; top:8px; display:none;filter:alpha(opacity=0);opacity:0}  
.file1 { padding:2px 10px; display:block; float:left; background:#FF66CC; color:#fff; z-index:1; margin-left:5px; vertical-align:middle; cursor: pointer}  
.inputstyle { width:150px; border:1px solid #888; z-index:99}
  • 写回答

1条回答 默认 最新

  • lshen01 2023-03-16 19:42
    关注

    参考GPT和自己的思路:

    要实现在画布上上传图片并可以绘制,你需要添加一个 input 元素,类型为 file,用于选择本地图片。然后监听 input 元素的 change 事件,在回调函数中获取选择的文件,创建一个 Image 对象,将文件路径赋值给 Image 对象的 src 属性,等待图片加载完毕后,将图片绘制到画布上。

    下面是代码实现:

    const fileInput = document.getElementById("upload");
    
    fileInput.addEventListener("change", function (event) {
      const file = event.target.files[0];
      const image = new Image();
      const reader = new FileReader();
      reader.onload = function () {
        image.src = reader.result;
        image.onload = function () {
          const canvas = document.getElementById("drawing-board");
          const ctx = canvas.getContext("2d");
          ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height);
        };
      };
      reader.readAsDataURL(file);
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码