目錄
HTML程式碼:
Javascript程式碼:
首頁 web前端 H5教程 超酷的HTML5 Canvas網路畫板程式碼範例詳解

超酷的HTML5 Canvas網路畫板程式碼範例詳解

Mar 09, 2017 pm 03:54 PM

超酷的HTML5 Canvas網路畫板程式碼範例詳解

在今天的HTML教學裡,我們要學習如何使用HTML5 Canvas實作一個超酷又簡單的網絡畫板功能。在這個教學中,我們可以選擇筆刷的類型、筆刷的大小以及筆刷的顏色,當然作為畫板還需要很多功能,這裡只是最基本的繪製功能,大家可以自己實現類似矩形、橢圓等複雜元素的繪製。

超酷的HTML5 Canvas網路畫板程式碼範例詳解

你也可以再這裡查看DEMO示範

下面我們來簡單地分析一下實作這個HTML5網頁畫板的原理及程式碼,程式碼由HTML以及Javascript組成,主要還是Javascript程式碼。

HTML程式碼:

<p style="width:530px;margin:10px auto">
    <p id="canvasp"></p>
</p>
登入後複製

HTML程式碼非常簡單,只是建構了一個canvas容器,我們的畫板就在這個地方產生。

Javascript程式碼:

首先我們透過一組變數來定義畫板的樣式,以及一些資料的初始化:

var canvas;
var context;
var canvasWidth = 490;
var canvasHeight = 220;
var padding = 25;
var lineWidth = 8;
var colorPurple = "#cb3594";
var colorGreen = "#659b41";
var colorYellow = "#ffcf33";
var colorBrown = "#986928";
var outlineImage = new Image();
var crayonImage = new Image();
var markerImage = new Image();
var eraserImage = new Image();
var crayonBackgroundImage = new Image();
var markerBackgroundImage = new Image();
var eraserBackgroundImage = new Image();
var crayonTextureImage = new Image();
var clickX = new Array();
var clickY = new Array();
var clickColor = new Array();
var clickTool = new Array();
var clickSize = new Array();
var clickDrag = new Array();
var paint = false;
var curColor = colorPurple;
var curTool = "crayon";
var curSize = "normal";
var mediumStartX = 18;
var mediumStartY = 19;
var mediumImageWidth = 93;
var mediumImageHeight = 46;
var drawingAreaX = 111;
var drawingAreaY = 11;
var drawingAreaWidth = 267;
var drawingAreaHeight = 200;
var toolHotspotStartY = 23;
var toolHotspotHeight = 38;
var sizeHotspotStartY = 157;
var sizeHotspotHeight = 36;
var sizeHotspotWidthObject = new Object();
sizeHotspotWidthObject.huge = 39;
sizeHotspotWidthObject.large = 25;
sizeHotspotWidthObject.normal = 18;
sizeHotspotWidthObject.small = 16;
var totalLoadResources = 8;
var curLoadResNum = 0;
登入後複製

接下來開始準備畫布,也就是初始化Canvas物件:

function prepareCanvas()
{
    // Create the canvas (Neccessary for IE because it doesn&#39;t know what a canvas element is)
    var canvasp = document.getElementById(&#39;canvasp&#39;);
    canvas = document.createElement(&#39;canvas&#39;);
    canvas.setAttribute(&#39;width&#39;, canvasWidth);
    canvas.setAttribute(&#39;height&#39;, canvasHeight);
    canvas.setAttribute(&#39;id&#39;, &#39;canvas&#39;);
    canvasp.appendChild(canvas);
    if(typeof G_vmlCanvasManager != &#39;undefined&#39;) {
        canvas = G_vmlCanvasManager.initElement(canvas);
    }
    context = canvas.getContext("2d"); // Grab the 2d canvas context
    // Note: The above code is a workaround for IE 8 and lower. Otherwise we could have used:
    //     context = document.getElementById(&#39;canvas&#39;).getContext("2d");

    // Load images
    // -----------
    crayonImage.onload = function() { resourceLoaded(); 
    };
    crayonImage.src = "images/crayon-outline.png";
    //context.drawImage(crayonImage, 0, 0, 100, 100);

    markerImage.onload = function() { resourceLoaded(); 
    };
    markerImage.src = "images/marker-outline.png";

    eraserImage.onload = function() { resourceLoaded(); 
    };
    eraserImage.src = "images/eraser-outline.png";    

    crayonBackgroundImage.onload = function() { resourceLoaded(); 
    };
    crayonBackgroundImage.src = "images/crayon-background.png";

    markerBackgroundImage.onload = function() { resourceLoaded(); 
    };
    markerBackgroundImage.src = "images/marker-background.png";

    eraserBackgroundImage.onload = function() { resourceLoaded(); 
    };
    eraserBackgroundImage.src = "images/eraser-background.png";

    crayonTextureImage.onload = function() { resourceLoaded(); 
    };
    crayonTextureImage.src = "images/crayon-texture.png";

    outlineImage.onload = function() { resourceLoaded(); 
    };
    outlineImage.src = "images/watermelon-duck-outline.png";

    // Add mouse events
    // ----------------
    $(&#39;#canvas&#39;).mousedown(function(e)
    {
        // Mouse down location
        var mouseX = e.pageX - this.offsetLeft;
        var mouseY = e.pageY - this.offsetTop;

        if(mouseX < drawingAreaX) // Left of the drawing area
        {
            if(mouseX > mediumStartX)
            {
                if(mouseY > mediumStartY && mouseY < mediumStartY + mediumImageHeight){
                    curColor = colorPurple;
                }else if(mouseY > mediumStartY + mediumImageHeight && mouseY < mediumStartY + mediumImageHeight * 2){
                    curColor = colorGreen;
                }else if(mouseY > mediumStartY + mediumImageHeight * 2 && mouseY < mediumStartY + mediumImageHeight * 3){
                    curColor = colorYellow;
                }else if(mouseY > mediumStartY + mediumImageHeight * 3 && mouseY < mediumStartY + mediumImageHeight * 4){
                    curColor = colorBrown;
                }
            }
        }
        else if(mouseX > drawingAreaX + drawingAreaWidth) // Right of the drawing area
        {
            if(mouseY > toolHotspotStartY)
            {
                if(mouseY > sizeHotspotStartY)
                {
                    var sizeHotspotStartX = drawingAreaX + drawingAreaWidth;
                    if(mouseY < sizeHotspotStartY + sizeHotspotHeight && mouseX > sizeHotspotStartX)
                    {
                        if(mouseX < sizeHotspotStartX + sizeHotspotWidthObject.huge){
                            curSize = "huge";
                        }else if(mouseX < sizeHotspotStartX + sizeHotspotWidthObject.large + sizeHotspotWidthObject.huge){
                            curSize = "large";
                        }else if(mouseX < sizeHotspotStartX + sizeHotspotWidthObject.normal + 
                        sizeHotspotWidthObject.large + sizeHotspotWidthObject.huge){
                            curSize = "normal";
                        }else if(mouseX < sizeHotspotStartX + sizeHotspotWidthObject.small + 
                        sizeHotspotWidthObject.normal + sizeHotspotWidthObject.large + sizeHotspotWidthObject.huge){
                            curSize = "small";                        
                        }
                    }
                }
                else
                {
                    if(mouseY < toolHotspotStartY + toolHotspotHeight){
                        curTool = "crayon";
                    }else if(mouseY < toolHotspotStartY + toolHotspotHeight * 2){
                        curTool = "marker";
                    }else if(mouseY < toolHotspotStartY + toolHotspotHeight * 3){
                        curTool = "eraser";
                    }
                }
            }
        }
        else if(mouseY > drawingAreaY && mouseY < drawingAreaY + drawingAreaHeight)
        {
            // Mouse click location on drawing area
        }
        paint = true;
        addClick(mouseX, mouseY, false);
        redraw();
    });

    $(&#39;#canvas&#39;).mousemove(function(e){
        if(paint==true){
            addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
            redraw();
        }
    });

    $(&#39;#canvas&#39;).mouseup(function(e){
        paint = false;
          redraw();
    });

    $(&#39;#canvas&#39;).mouseleave(function(e){
        paint = false;
    });
}
登入後複製

看起來很複雜,前面主要是初始化canvas的背景圖片,後面主要是初始化畫筆事件,像是click、mouseup、mouseleave等滑鼠事件。

以下是draw的主要方法:

function redraw()
{
    // Make sure required resources are loaded before redrawing
    if(curLoadResNum < totalLoadResources){ return; }

    clearCanvas();

    var locX;
    var locY;
    if(curTool == "crayon")
    {
        // Draw the crayon tool background
        context.drawImage(crayonBackgroundImage, 0, 0, canvasWidth, canvasHeight);

        // Purple
        locX = (curColor == colorPurple) ? 18 : 52;
        locY = 19;

        context.beginPath();
        context.moveTo(locX + 41, locY + 11);
        context.lineTo(locX + 41, locY + 35);
        context.lineTo(locX + 29, locY + 35);
        context.lineTo(locX + 29, locY + 33);
        context.lineTo(locX + 11, locY + 27);
        context.lineTo(locX + 11, locY + 19);
        context.lineTo(locX + 29, locY + 13);
        context.lineTo(locX + 29, locY + 11);
        context.lineTo(locX + 41, locY + 11);
        context.closePath();
        context.fillStyle = colorPurple;
        context.fill();    

        if(curColor == colorPurple){
            context.drawImage(crayonImage, locX, locY, mediumImageWidth, mediumImageHeight);
        }else{
            context.drawImage(crayonImage, 0, 0, 59, mediumImageHeight, locX, locY, 59, mediumImageHeight);
        }

        // Green
        locX = (curColor == colorGreen) ? 18 : 52;
        locY += 46;

        context.beginPath();
        context.moveTo(locX + 41, locY + 11);
        context.lineTo(locX + 41, locY + 35);
        context.lineTo(locX + 29, locY + 35);
        context.lineTo(locX + 29, locY + 33);
        context.lineTo(locX + 11, locY + 27);
        context.lineTo(locX + 11, locY + 19);
        context.lineTo(locX + 29, locY + 13);
        context.lineTo(locX + 29, locY + 11);
        context.lineTo(locX + 41, locY + 11);
        context.closePath();
        context.fillStyle = colorGreen;
        context.fill();    

        if(curColor == colorGreen){
            context.drawImage(crayonImage, locX, locY, mediumImageWidth, mediumImageHeight);
        }else{
            context.drawImage(crayonImage, 0, 0, 59, mediumImageHeight, locX, locY, 59, mediumImageHeight);
        }

        // Yellow
        locX = (curColor == colorYellow) ? 18 : 52;
        locY += 46;

        context.beginPath();
        context.moveTo(locX + 41, locY + 11);
        context.lineTo(locX + 41, locY + 35);
        context.lineTo(locX + 29, locY + 35);
        context.lineTo(locX + 29, locY + 33);
        context.lineTo(locX + 11, locY + 27);
        context.lineTo(locX + 11, locY + 19);
        context.lineTo(locX + 29, locY + 13);
        context.lineTo(locX + 29, locY + 11);
        context.lineTo(locX + 41, locY + 11);
        context.closePath();
        context.fillStyle = colorYellow;
        context.fill();    

        if(curColor == colorYellow){
            context.drawImage(crayonImage, locX, locY, mediumImageWidth, mediumImageHeight);
        }else{
            context.drawImage(crayonImage, 0, 0, 59, mediumImageHeight, locX, locY, 59, mediumImageHeight);
        }

        // Yellow
        locX = (curColor == colorBrown) ? 18 : 52;
        locY += 46;

        context.beginPath();
        context.moveTo(locX + 41, locY + 11);
        context.lineTo(locX + 41, locY + 35);
        context.lineTo(locX + 29, locY + 35);
        context.lineTo(locX + 29, locY + 33);
        context.lineTo(locX + 11, locY + 27);
        context.lineTo(locX + 11, locY + 19);
        context.lineTo(locX + 29, locY + 13);
        context.lineTo(locX + 29, locY + 11);
        context.lineTo(locX + 41, locY + 11);
        context.closePath();
        context.fillStyle = colorBrown;
        context.fill();    

        if(curColor == colorBrown){
            context.drawImage(crayonImage, locX, locY, mediumImageWidth, mediumImageHeight);
        }else{
            context.drawImage(crayonImage, 0, 0, 59, mediumImageHeight, locX, locY, 59, mediumImageHeight);
        }
    }
    else if(curTool == "marker")
    {
        // Draw the marker tool background
        context.drawImage(markerBackgroundImage, 0, 0, canvasWidth, canvasHeight);

        // Purple
        locX = (curColor == colorPurple) ? 18 : 52;
        locY = 19;

        context.beginPath();
        context.moveTo(locX + 10, locY + 24);
        context.lineTo(locX + 10, locY + 24);
        context.lineTo(locX + 22, locY + 16);
        context.lineTo(locX + 22, locY + 31);
        context.closePath();
        context.fillStyle = colorPurple;
        context.fill();    

        if(curColor == colorPurple){
            context.drawImage(markerImage, locX, locY, mediumImageWidth, mediumImageHeight);
        }else{
            context.drawImage(markerImage, 0, 0, 59, mediumImageHeight, locX, locY, 59, mediumImageHeight);
        }

        // Green
        locX = (curColor == colorGreen) ? 18 : 52;
        locY += 46;

        context.beginPath();
        context.moveTo(locX + 10, locY + 24);
        context.lineTo(locX + 10, locY + 24);
        context.lineTo(locX + 22, locY + 16);
        context.lineTo(locX + 22, locY + 31);
        context.closePath();
        context.fillStyle = colorGreen;
        context.fill();    

        if(curColor == colorGreen){
            context.drawImage(markerImage, locX, locY, mediumImageWidth, mediumImageHeight);
        }else{
            context.drawImage(markerImage, 0, 0, 59, mediumImageHeight, locX, locY, 59, mediumImageHeight);
        }

        // Yellow
        locX = (curColor == colorYellow) ? 18 : 52;
        locY += 46;

        context.beginPath();
        context.moveTo(locX + 10, locY + 24);
        context.lineTo(locX + 10, locY + 24);
        context.lineTo(locX + 22, locY + 16);
        context.lineTo(locX + 22, locY + 31);
        context.closePath();
        context.fillStyle = colorYellow;
        context.fill();    

        if(curColor == colorYellow){
            context.drawImage(markerImage, locX, locY, mediumImageWidth, mediumImageHeight);
        }else{
            context.drawImage(markerImage, 0, 0, 59, mediumImageHeight, locX, locY, 59, mediumImageHeight);
        }

        // Yellow
        locX = (curColor == colorBrown) ? 18 : 52;
        locY += 46;

        context.beginPath();
        context.moveTo(locX + 10, locY + 24);
        context.lineTo(locX + 10, locY + 24);
        context.lineTo(locX + 22, locY + 16);
        context.lineTo(locX + 22, locY + 31);
        context.closePath();
        context.fillStyle = colorBrown;
        context.fill();    

        if(curColor == colorBrown){
            context.drawImage(markerImage, locX, locY, mediumImageWidth, mediumImageHeight);
        }else{
            context.drawImage(markerImage, 0, 0, 59, mediumImageHeight, locX, locY, 59, mediumImageHeight);
        }
    }
    else if(curTool == "eraser")
    {
        context.drawImage(eraserBackgroundImage, 0, 0, canvasWidth, canvasHeight);
        context.drawImage(eraserImage, 18, 19, mediumImageWidth, mediumImageHeight);    
    }else{
        alert("Error: Current Tool is undefined");
    }

    if(curSize == "small"){
        locX = 467;
    }else if(curSize == "normal"){
        locX = 450;
    }else if(curSize == "large"){
        locX = 428;
    }else if(curSize == "huge"){
        locX = 399;
    }
    locY = 189;
    context.beginPath();
    context.rect(locX, locY, 2, 12);
    context.closePath();
    context.fillStyle = &#39;#333333&#39;;
    context.fill();    

    // Keep the drawing in the drawing area
    context.save();
    context.beginPath();
    context.rect(drawingAreaX, drawingAreaY, drawingAreaWidth, drawingAreaHeight);
    context.clip();

    var radius;
    var i = 0;
    for(; i < clickX.length; i++)
    {        
        if(clickSize[i] == "small"){
            radius = 2;
        }else if(clickSize[i] == "normal"){
            radius = 5;
        }else if(clickSize[i] == "large"){
            radius = 10;
        }else if(clickSize[i] == "huge"){
            radius = 20;
        }else{
            alert("Error: Radius is zero for click " + i);
            radius = 0;    
        }

        context.beginPath();
        if(clickDrag[i] && i){
            context.moveTo(clickX[i-1], clickY[i-1]);
        }else{
            context.moveTo(clickX[i], clickY[i]);
        }
        context.lineTo(clickX[i], clickY[i]);
        context.closePath();

        if(clickTool[i] == "eraser"){
            //context.globalCompositeOperation = "destination-out"; // To erase instead of draw over with white
            context.strokeStyle = &#39;white&#39;;
        }else{
            //context.globalCompositeOperation = "source-over";    // To erase instead of draw over with white
            context.strokeStyle = clickColor[i];
        }
        context.lineJoin = "round";
        context.lineWidth = radius;
        context.stroke();

    }
    //context.globalCompositeOperation = "source-over";// To erase instead of draw over with white
    context.restore();

    // Overlay a crayon texture (if the current tool is crayon)
    if(curTool == "crayon"){
        context.globalAlpha = 0.4; // No IE support
        context.drawImage(crayonTextureImage, 0, 0, canvasWidth, canvasHeight);
    }
    context.globalAlpha = 1; // No IE support

    // Draw the outline image
    context.drawImage(outlineImage, drawingAreaX, drawingAreaY, drawingAreaWidth, drawingAreaHeight);
}
登入後複製

其實HTML5說白了還是需要很多Javascript支持,不過Canvas非常不錯,可以讓你在上面自由地繪製圖形和動畫。這款以HTML5 Canvas為基礎的網頁畫板就是一個很好的例子。原始碼下載>>







############## ################## ###

以上是超酷的HTML5 Canvas網路畫板程式碼範例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
4 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

HTML 中的表格邊框 HTML 中的表格邊框 Sep 04, 2024 pm 04:49 PM

HTML 表格邊框指南。在這裡,我們以 HTML 中的表格邊框為例,討論定義表格邊框的多種方法。

HTML 左邊距 HTML 左邊距 Sep 04, 2024 pm 04:48 PM

HTML 左邊距指南。在這裡,我們討論 HTML margin-left 的簡要概述及其範例及其程式碼實作。

HTML 中的巢狀表 HTML 中的巢狀表 Sep 04, 2024 pm 04:49 PM

這是 HTML 中巢狀表的指南。這裡我們討論如何在表中建立表格以及對應的範例。

HTML 表格佈局 HTML 表格佈局 Sep 04, 2024 pm 04:54 PM

HTML 表格佈局指南。在這裡,我們詳細討論 HTML 表格佈局的值以及範例和輸出。

HTML 輸入佔位符 HTML 輸入佔位符 Sep 04, 2024 pm 04:54 PM

HTML 輸入佔位符指南。在這裡,我們討論 HTML 輸入佔位符的範例以及程式碼和輸出。

HTML 有序列表 HTML 有序列表 Sep 04, 2024 pm 04:43 PM

HTML 有序列表指南。在這裡我們也分別討論了 HTML 有序列表和類型的介紹以及它們的範例

在 HTML 中移動文字 在 HTML 中移動文字 Sep 04, 2024 pm 04:45 PM

HTML 中的文字移動指南。在這裡我們討論一下marquee標籤如何使用語法和實作範例。

HTML onclick 按鈕 HTML onclick 按鈕 Sep 04, 2024 pm 04:49 PM

HTML onclick 按鈕指南。這裡我們分別討論它們的介紹、工作原理、範例以及各個事件中的onclick事件。

See all articles