使用Canvas制作畫圖工具


  前  言

JRedu

 canvas是HTML5中重要的元素之一,canvas元素使用JavaScript在網頁上繪制圖像,畫布是一個矩形區域,我們可以控制其每一個元素,並且canvas擁有多種的繪制路徑、矩形、圓形、字符以及添加圖像的方法。 這一章我們使用canvas來做一個畫圖工具,並且支持下載圖片功能。

 

最終實現界面

最終實現界面如下,當然我這種手殘黨是畫不出來,手動@陳沖老師畫的:

畫圖工具實現的主要功能

 

1.畫筆顏色和粗細點擊選取

2.橡皮擦

3.清除畫布

4.下載圖片

在實現主要功能之前,首先要放置canvas畫布,實現在規定區域內隨意畫圖的功能,實現的原理是獲取鼠標點擊之后的位置,利用鼠標的點擊、移動事件來實現繪畫。實現代碼如下:

設置全局變量

 

var canvas = document.getElementById('canvas');
var cvs = canvas.getContext('2d');  
var drawing =false;

 

Html代碼

<canvas id="canvas" width="800px" height="600px" style="border: 1px solid red;"></canvas>

Js代碼

window.onload = function(){
var penWeight = 0;      //畫筆粗細  
var penColor = '';  //畫筆顏色  
canvas.onmousedown = function(e){  
/*找到鼠標(畫筆)的坐標*/  
var start_x = e.clientX - canvas.offsetLeft + document.body.scrollLeft;  
var start_y = e.clientY - canvas.offsetTop + document.body.scrollTop;  
cvs.beginPath();    //開始本次繪畫  
cvs.moveTo(start_x, start_y);   //畫筆起始點  
/*設置畫筆屬性*/  
cvs.lineCap = 'round';  
cvs.lineJoin ="round";  
cvs.strokeStyle = penColor;     //畫筆顏色  
cvs.lineWidth = penWeight;      //畫筆粗細  
canvas.onmousemove = function(e){  
      /*找到鼠標(畫筆)的坐標*/  
      var move_x = e.clientX - canvas.offsetLeft + document.body.scrollLeft;  
      var move_y = e.clientY - canvas.offsetTop + document.body.scrollTop;   
      cvs.lineTo(move_x, move_y);     //根據鼠標路徑繪畫  
        cvs.stroke();   //立即渲染  
        }
      canvas.onmouseup = function(e){
            cvs.closePath();    //結束本次繪畫
            canvas.onmousemove = null;  
            canvas.onmouseup = null;  
        }  
        canvas.onmouseleave = function(){
            cvs.closePath();
            canvas.onmousemove = null;  
            canvas.onmouseup = null; 
        }
}
}

 

1畫筆顏色和粗細點擊選取

這里我分別從畫筆顏色和畫筆粗細中個選取一個作為例子來簡述以下如何實現:

從上邊的代碼中可以了解到控制畫筆粗細和顏色的分別是penWeight和penColor,也就是說,我們可以通過修改這兩個變量從而實現改變畫筆屬性的功能,代碼如下:

Html代碼

<input type="button" value="粗" class="bold btn" onclick="checkpen(10)" />
<input type="button" value="紅" class="red item" style="background-color: red;border: none;" onclick="changecolor('red')"  />

Js代碼

function checkpen(width){ //設置筆的粗細
        cvs.lineWidth = width;
    }
    function changecolor(pencolor){ //設置顏色
        cvs.strokeStyle =pencolor;
    }

 

2橡皮擦

選中橡皮擦之后提示正在使用利用鼠標移動點擊事件實現橡皮擦的功能其中cvs.globalCompositeOperation = "destination-out";  可以實現橡皮擦點擊經過的地方顯示原始背景色。代碼實現如下:

Html代碼

<input type="button" value="橡皮擦" class="eraser btn"   id="eraser" onclick="checkeraser()" />
<input type="button" value="取消橡皮擦" class="uneraser btn" id="uneraser" onclick="canceleraser()" />

Js代碼

 

//選中橡皮擦
function checkeraser(){
document.getElementById("eraser").value = "正在使用...";
cvs.lineWidth = 20;
cvs.globalCompositeOperation = "destination-out";  
    function getBoundingClientRect(x,y){
    var box = canvas.getBoundingClientRect(); //獲取canvas的距離瀏覽器視窗的上下左右距離
    return {x:x-box.left,
            y:y-box.top
    }
}
canvas.onmousedown = function(e){
    var first = getBoundingClientRect(e.clientX,e.clientY);
    cvs.save();
    cvs.beginPath();
    cvs.moveTo(first.x,first.y);
    drawing = true;
}
canvas.onmousemove = function(e){
    if(drawing){
        var move = getBoundingClientRect(e.clientX,e.clientY);
        cvs.save();
        cvs.lineTo(move.x,move.y);
        cvs.stroke()
        cvs.restore()
    }
}
canvas.onmouseup = function(){
    drawing = false;
}
canvas.onmouseleave = function(){
    drawing = false;
    canvas.onmouseup();
}
}

 

3清除畫布

清空畫布只需要調用clearRect() 方法實現清空給定矩形內的指定像素。代碼如下: 

Html代碼

<input type="button" value="清除畫布" class="clear fun" onclick="clearb()" />

Js代碼

//清除畫布功能
    function clearb (){
        cvs.clearRect(0,0,800,800);
}

 

4下載圖片

下載圖片的部分代碼和生成畫布實現繪畫的代碼寫在同一個方法中,一並貼出來了,可以自行刪改。以下是實現代碼:

Html代碼

<input type="button" value="清除畫布" class="clear fun" onclick="clearb()" />

Js代碼

 

//保存圖片
window.onload = function(){
    var penWeight = 0;      //畫筆粗細  
    var penColor = '';  //畫筆顏色  
    canvas.onmousedown = function(e){  
        /*找到鼠標(畫筆)的坐標*/  
        var start_x = e.clientX - canvas.offsetLeft + document.body.scrollLeft;  
        var start_y = e.clientY - canvas.offsetTop + document.body.scrollTop;  
        cvs.beginPath();    //開始本次繪畫  
          cvs.moveTo(start_x, start_y);   //畫筆起始點  
          /*設置畫筆屬性*/  
        cvs.lineCap = 'round';  
        cvs.lineJoin ="round";  
        cvs.strokeStyle = penColor;     //畫筆顏色  
        cvs.lineWidth = penWeight;      //畫筆粗細  
        canvas.onmousemove = function(e){  
              /*找到鼠標(畫筆)的坐標*/  
            var move_x = e.clientX - canvas.offsetLeft + document.body.scrollLeft;  
            var move_y = e.clientY - canvas.offsetTop + document.body.scrollTop;  
            cvs.lineTo(move_x, move_y);     //根據鼠標路徑繪畫  
  
            cvs.stroke();   //立即渲染  
        }  
        canvas.onmouseup = function(e){  
            cvs.closePath();    //結束本次繪畫  
            canvas.onmousemove = null;  
            canvas.onmouseup = null;  
        }  
        canvas.onmouseleave = function(){
            cvs.closePath();
            canvas.onmousemove = null;  
            canvas.onmouseup = null; 
        }
    } 
      var dlButton = document.getElementById("downloadImageBtn");
    bindButtonEvent(dlButton,"click",saveAsLocalImage)
}
function bindButtonEvent(element, type, handler)
            {
                   if(element.addEventListener) {
                      element.addEventListener(type, handler, false);
                   } else {
                      element.attachEvent('on'+type, handler);
                   }
            }
  function saveAsLocalImage () {
                var myCanvas = document.getElementById("canvas");
                var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); 
                window.location.href=image; 
            }

 

如需源碼,可戳右側鏈接自行下載哦~http://www.jredu100.com/index.php?m=content&c=index&a=show&catid=65&id=39

 

 

作者:傑瑞教育
出處: http://www.cnblogs.com/jerehedu/ 
版權聲明:本文版權歸 傑瑞教育 技有限公司和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。
技術咨詢:JRedu技術交流

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM