所有分类
  • 所有分类
  • 后端开发
HTML5 Canvas:网页上的绘画神器

HTML5 Canvas:网页上的绘画神器

Canvas网络画板代码示例详解canvas实现一个超酷而又简单的网络画板功能。下面我们来简单地分析一下实现这个HTML5网页画板的原理及代码,代码由HTML以及Javascript组成,主要还是Javascript代码。

HTML5 Canvas简介

你知道吗?canvas这种新科技就是HTML5弄出来的。有了这个,我们就能在网页上随心所欲地画画了。不论是形状还是动画,都不在话下。而且,它还能处理图片和游戏设计。对于那些需要展示图片的人,canvas简直是神器!如果你想要做在线绘画板之类的活动,canvas也很容易做到!

Canvas容器构建

赶紧去网上画画!首要任务就是搞懂这个Canvas容器,这可是我们大展身手的舞台。用HTML敲打几行代码,就能在网页上轻松显现出Canvas元素了,之后别忘了把它的尺寸调到合适的大小:

html
HTML5 Canvas:网页上的绘画神器

知道吗,这儿有个叫做”myCanvas”的Canvas小助手,尺寸有800*600。就像一块画板在那儿等着我们发挥创意!

Javascript代码实现

赶紧来玩玩咱们这个JavaScript画板!首先,定个你想要的画笔大小、颜色等要素。接下来,用JavaScript轻轻松松建立个Canvas对象,别忘了先准备好画布!

“`javascript

咱们就在文档中找那个叫做”myCanvas”的东东,它就叫做 canvas。

咱这儿有个画布神器呐!直接用ctx[‘2d’]能让你玩转图像处理~

框框就用白色填充,这样看起来舒服点。

记住,先把整个画布涂成黑色: ctx.fillStyle =’black’;接下来就是简单的 ctx.fillRect(0,0, canvas.width, canvas.height);这两句话就能搞定!

这段代码就是去找个叫”myCanvas”的Canvas,找到了就把它的2D渲染环境搞定。然后,把画布变成全白色就行!

绘制功能实现

下边儿重要!你知道怎么用那个画图功能吗?其实,就是看鼠标不停地在屏幕上移来移去,然后赶紧跟着画出线来。要是鼠标一放,那就不要犹豫,立马停下来。所以掌握这个画图功能的秘诀就是抓住时机,跟着鼠标走!

var isDrawing = false;

var lastX =0;

var lastY =0;

function draw(e){

if (!isDrawing) return;

咱们先把画笔颜色设成黑色。

ctx.lineWidth =5;//画笔粗细

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;

ctx.lineJoin =’round’;

ctx.lineCap =’round’;

ctx.beginPath();

ctx.moveTo(lastX, lastY);

“看这儿,简单调整一下句子的结构就搞掂了。只要把最后那段去掉就行了:只需要删除ctx.lineTo(e.offsetX,e.offsetY)这个部分,忽略它就Ok啦!”

ctx.stroke();

lastX =e.offsetX;

function prepareCanvas()
{
    // Create the canvas (Neccessary for IE because it doesn't know what a canvas element is)
    var canvasp = document.getElementById('canvasp');
    canvas = document.createElement('canvas');
    canvas.setAttribute('width', canvasWidth);
    canvas.setAttribute('height', canvasHeight);
    canvas.setAttribute('id', 'canvas');
    canvasp.appendChild(canvas);
    if(typeof G_vmlCanvasManager != 'undefined') {
        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('canvas').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
    // ----------------
    $('#canvas').mousedown(function(e)
    {
        // Mouse down location
        var mouseX = e.pageX - this.offsetLeft;
        var mouseY = e.pageY - this.offsetTop;
        if(mouseX  mediumStartX)
            {
                if(mouseY > mediumStartY && mouseY  mediumStartY + mediumImageHeight && mouseY  mediumStartY + mediumImageHeight * 2 && mouseY  mediumStartY + mediumImageHeight * 3 && mouseY  drawingAreaX + drawingAreaWidth) // Right of the drawing area
        {
            if(mouseY > toolHotspotStartY)
            {
                if(mouseY > sizeHotspotStartY)
                {
                    var sizeHotspotStartX = drawingAreaX + drawingAreaWidth;
                    if(mouseY  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  drawingAreaY && mouseY < drawingAreaY + drawingAreaHeight)
        {
            // Mouse click location on drawing area
        }
        paint = true;
        addClick(mouseX, mouseY, false);
        redraw();
    });
    $('#canvas').mousemove(function(e){
        if(paint==true){
            addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
            redraw();
        }
    });
    $('#canvas').mouseup(function(e){
        paint = false;
          redraw();
    });
    $('#canvas').mouseleave(function(e){
        paint = false;
    });
}

lastY =e.offsetY;

}

isDrawing = true;

});

你手在画布上动吗?鼠标放上去,就开始画!

鼠标松开时,触发的操作是啥?就是——

isDrawing = false;

只要你的鼠标离开了画布,就能触发一个叫作’ mouseleave ‘的动作!

想要做出这个能动的画图结果吗?简单来说就是操练好 mousedown (鼠标左键点击一次), mousemove (晃动鼠标), mouseup (松开鼠标左键)和 mouseleave (鼠标离开区域)这几个动作就够了。把鼠标左键按下去就能开始你的绘画之旅了;滑动你的鼠标,线条会跟随着你的痕迹不断延伸;要是你手一抖放开鼠标或者移出了绘画区域,条子也会立马停下为止。

总结与展望

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 = '#333333';
    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 = 'white';
        }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);
}

看完这个网页绘图板使用HTML5Canvas和JavaScript的小教程后,你就可以轻松学会做好看实用的网络画板!而且我们还能加点好玩的,比如画出各种各样的立体图形、圆啊、矩形什么的。

HTML5Canvas技术,以后肯定会有大突破,你们可别错过了哟~看完上面的文章,记得赶快动动手,自己挖掘更多好用又有趣的网页开发小技巧!

原文链接:https://www.icz.com/technicalinformation/web/2024/04/14330.html,转载请注明出处~~~
0

评论0

请先
注意:请收藏好网址www.icz.com,防止失联!站内免费资源持续上传中…!赞助我们
显示验证码
没有账号?注册  忘记密码?