html5 canvas 塗鴉畫板

來源:互聯網
上載者:User

標籤:style   http   color   java   os   使用   io   檔案   for   

html5 canvas 的塗鴉畫板,可以載入圖片進行塗鴉,也可以下載
伺服器使用的php
上傳的圖片不能超過1M,只能是jpg或者png 格式的
示範地址的伺服器網速不怎麼樣,讀取檔案可能很慢,到達100%的時候點擊讀取檔案,如果沒顯示就多點幾次
?1. [代碼]首頁面     

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>塗鴉畫板</title>
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<link href="index.css" rel="stylesheet" type="text/css">
 
</head>
<body>
    <div id="chooseColor"></div>
    <div id="chooseSize"></div>
    <div id="paint">
        <canvas id="pad" width="800" height="600" />
    </div>
    <input type="button" id="download" value="下載" />
    <!-- 上傳圖片  -->
    <input type="file" name="mypic" id="chooseFile" />
    <input type="button" value="讀取檔案" id="load" />
    <!-- 進度條 -->
    <div class="progress">
        <span class="bar"></span><span class="percent">0%</span >
    </div>
    <!-- 隱藏地區 -->
    <img id="tulip" src="" alt="載入顯示區" />
</body>
<script type="text/javascript" src="index.js"></script>
</html>
2. [代碼]頁面的簡單排版     
body,input {
    font-size: 9pt;
}
 
#paint,#chooseSize {
    clear: both;
}
 
.option {
    float: left;
    width: 20px;
    height: 20px;
    border: 2px solid #cccccc;
    margin-right: 4px;
    margin-bottom: 4px;
}
 
.active {
    border: 2px solid black;
}
 
.lw {
    text-align: center;
    vertical-align: middle;
}
 
img.output {
    border: 1px solid green;
}
 
#pad {
    border: 2px solid gray;
    cursor: arrow;
}
 
#chooseFile {
    float: left;
    width: 140px;
}
 
#tulip {
    display: none;
}
 
#download {
    margin-left: 550px;
}
 
#load {
    float: left;
    width: 80px;
}
3. [代碼]畫圖,上傳,下載處理     

$(document).ready(function() {
    paint();
    downloadPic();
    loadImg();
    uploadImg();
});
 
/**
 * 繪畫
 */
function paint() {
    chooseColor();
    chooseSize();
    canvas();
}
 
/**
 * 顏色選取器
 */
function chooseColor() {
    var colors = "red;orange;yellow;green;blue;indigo;purple;black;white".split(‘;‘);
    var sb = [];
    $.each(colors,function(i,v){
        sb.push("<div class=‘option‘ style=‘background-color:" + v + "‘></div>");
    });
    $("#chooseColor").html(sb.join("\n"));
}
 
/**
 * 大小選取器
 */
function chooseSize(){
    sb = [];
    for (var i = 1; i <= 9; i++) sb.push("<div class=‘option lw‘>" + "<div style=‘margin-top:#px;margin-left:#px;width:%px;height:%px‘></div></div>".replace(/%/g, i).replace(/#/g, 10 - i / 2));
    $("#chooseSize").html(sb.join(‘\n‘));
}
 
/**
 * 畫圖
 */
function canvas(){
    var $clrs = $("#chooseColor .option");
    var $lws = $("#chooseSize .option");
    $clrs.click(function(){
        $clrs.removeClass("active");
        $(this).addClass("active");
        p_color = this.style.backgroundColor;
        $lws.children("div").css("background-color",p_color);
    }).first().click();
     
    //點選線條寬度選項時切換焦點並取得寬度存入p_width
    $lws.click(function(){
        $lws.removeClass("active");
        $(this).addClass("active");
        p_width = $(this).children("div").css("width").replace("px","");
         
    }).eq(3).click();
     
    // 取得canvas context
    var $canvas = $("#pad");
    var ctx = $canvas[0].getContext("2d");
    ctx.lineCap = "round";
    ctx.fillStyle = "white"; //整個canvas塗上白色的背景,避免PNG的透明底色效果
    ctx.fillRect(0,0,$canvas.width(),$canvas.height());
    var drawMode = false;
     
    // canvas點選,移動,放開按鍵時進行繪圖動作
    $canvas.mousedown(function(e){
        ctx.beginPath();
        ctx.strokeStyle = p_color;
        ctx.lineWidth = p_width;
        ctx.moveTo(e.pageX - $canvas.position().left, e.pageY - $canvas.position().top);
        drawMode = true;
    }).mousemove(function(e){
        if(drawMode){
            ctx.lineTo(e.pageX - $canvas.position().left, e.pageY - $canvas.position().top);
            ctx.stroke();
        }
    }).mouseup(function(e){
        drawMode = false;
    });
}
 
/**
 * 下載當前所繪製的映像
 */
function downloadPic(){
    // 使用toDataURL()將圖轉換成png檔案
    var saveFile = function(data, filename) {
        var save_link = document.createElementNS(‘http://www.w3.org/1999/xhtml‘, ‘a‘);
        save_link.href = data;
        save_link.download = filename;
        var event = document.createEvent(‘MouseEvents‘);
        event.initMouseEvent(‘click‘, true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        save_link.dispatchEvent(event);婚紗攝影
    };http://www.huiyi8.com/hunsha/?
    $("#download").click(function() {
        var myCanvas = document.getElementById("pad");
        var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
        // window.location.href=image;
        var filename = ‘paint_‘ + (new Date()).getTime() + ‘.png‘;
        saveFile(image, filename);
    });
}
 
 
//擷取當前檔案名稱
function ch_(url){  
    url=url.split("\\");//這裡要將 \ 轉義一下
    var filename = url[url.length-1];
    return filename;
}
 
 
//載入隱藏模組中的圖片
function loadImg(){
    $(‘#load‘).click(function(){
        // 載入到canvas
        var c= document.getElementById("pad");
        var ctx = c.getContext("2d");
        var img=document.getElementById("tulip");
        ctx.drawImage(img,0,0);
    });
}
 
/**
 * 上傳圖片
 */
function uploadImg(){
    var bar = $(‘.bar‘);
    var percent = $(‘.percent‘);
    var showimg = $(‘#showimg‘);
    var progress = $(".progress");
    $("#chooseFile").wrap("<form id=‘myupload‘ action=‘upload.php‘ method=‘post‘ enctype=‘multipart/form-data‘></form>");
    $("#chooseFile").change(function(){
        $("#myupload").ajaxSubmit({
            dataType: ‘json‘,
            uploadProgress: function(event, position, total, percentComplete) {
                var percentVal = percentComplete + ‘%‘;
                bar.width(percentVal);
                percent.html(percentVal);
            },
            success: function(data){
                // alert(‘上傳成功‘);
                var file = $(‘#chooseFile‘).val();
                var filename = ch_(file);
                var src = ‘paint/‘ + filename;
                $(‘#tulip‘).attr(‘src‘,src);
            },
            error: function(xhr){
                alert(‘上傳失敗‘);
            }
        });
    });
}
4. [代碼]伺服器上傳處理   
<?php
$picname = $_FILES [‘mypic‘] [‘name‘];
$picsize = $_FILES [‘mypic‘] [‘size‘];
if ($picname != ‘‘) {
    if ($picsize > 1024000) {
        echo ‘圖片的大小不能超過1M‘;
        exit ();
    }
    $type = strstr ( $picname, ‘.‘ );
    if ($type != ‘.jpg‘ && $type != ‘.png‘) {
        echo ‘圖片格式不對‘;
        exit ();
    }
    $pics = $picname;
    // 上傳路徑
    $pic_path = ‘paint/‘ . $pics;
    move_uploaded_file ( $_FILES [‘mypic‘] [‘tmp_name‘], $pic_path );
}
$size = round ( $picsize / 1024, 2 );
$arr = array (
        ‘name‘ => $picname,
        ‘pic‘ => $pics,
        ‘size‘ => $size
);
echo json_encode ( $arr );
?>
?

html5 canvas 塗鴉畫板

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.