選擇本地的圖片當背景實現塗鴉功能

選擇本地的圖片當背景實現塗鴉功能

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        canvas{border:1px solid green;}
    </style>
</head>
<body>
選擇圖片:<input id="file" type="file">
<button onclick="restuya()">重新塗鴉</button>
<button onclick="saveTu();">保存圖片</button>
<hr>
<canvas id="canvas" width="1105" height="500">
    您的破瀏覽器不兼容,請升級!
</canvas>
<hr>
<div id="res"></div>
<script type="text/javascript">
    // 獲取 canvas 對象
    var canvas = document.getElementById('canvas');
    // 獲取繪圖環境
    var ctx = canvas.getContext('2d');

    var last = null;

    var file = document.getElementById('file');

    // 文件對象
    var filedata = null;

    // 鼠標按下
    canvas.onmousedown = function(){
        // 在鼠標按下後觸發鼠標移動事件
        canvas.onmousemove = move;
    }

    // 鼠標擡起取消鼠標移動的事件
    canvas.onmouseup = function(){
        canvas.onmousemove = null;
        last = null;
    }

    // 鼠標移出畫布時 移動事件也要取消。
    canvas.onmouseout = function(){
        canvas.onmousemove = null;
        last = null;
    }

    // 鼠標移動函數
    function move(e){
        // console.log(e.offsetX);
        if(last != null){
            ctx.beginPath();
            ctx.moveTo(last[0],last[1]);
            ctx.lineTo(e.offsetX,e.offsetY);
            ctx.stroke();
        }
        // 第一次觸發這個函數,只做一件事,把當前 鼠標的 x , y 的位置記錄下來
        // 做下一次 線段的 起始點。
        last = [e.offsetX,e.offsetY];

    }

    // 當文件域內容發生改變時觸發函數
    file.onchange = function(e){
        filedata = e.target.files[0];
        // 	實例化文件讀取對象
        drawImg(filedata)
    }


    // 重新在畫
    function restuya(){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        drawImg(filedata)
    }


    // 繪製圖片
    function drawImg(filedata){
        console.log(filedata)
        var readFile = new FileReader();

        readFile.readAsDataURL(filedata);
            console.log(readFile)

        // 圖片讀取成功
        readFile.onload = function(){
            // 結果
          console.log(this.result);
            // this.result;
            // 第一種方法
            var Img = new Image();
            Img.src = this.result;
           // console.log(Img.src)
         //   console.log(Img);
            Img.onload = function(){
                // 根據 圖片的 寬高 來 設置canvas 寬和高
                canvas.width = Img.width;
                canvas.height = Img.height;

                // console.log(Img.width);

                // canvas.width = 500;
                // canvas.width = 500;

                ctx.drawImage(Img,0,0);

            }
        }
    }


    // 保存圖片
    function saveTu(){
        var saveImage = canvas.toDataURL('image/png');
        document.getElementById('res').innerHTML = '<img src="'+saveImage+'">';
    }

</script>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章