Home Web Front-end H5 Tutorial Use canvas to design a simple drawing board

Use canvas to design a simple drawing board

Jun 19, 2017 am 11:12 AM
canvas drawing board

I talked about some of the basic knowledge of canvasAPI before. Just looking at the introduction of the API is really boring. I need something that can inspire my inner passion to motivate myself to learn, so I created a small example to accompany the learning of canvasAPI, like this Through the knowledge of API and the application of small examples, you can better understand these properties and methods of canvas, and you can also inspire your own inspiration and feeling to create canvas special effects. Well, please call me Lei Feng. , you’re welcome! The small example brought to you below is very simple. It is a simple drawing tool. Let’s take a look at the effect first!

Let me describe the effect first: there is a canvas and several buttons. The canvas is a drawing board that can draw any graphics. The button can set the brush color of the drawing board. , you can also clear the artboard. Of course, if you want to draw a unique painting, please right-click and save the picture as, you know!

How is this done?

I will explain the principle first and then post the code to make it easier for everyone to understand. I have already done this, so don’t just use it as a doctrine!

The principle is actually very simple. The core methods used here are lineTo() and stroke(). Students who have read the previous API articles should understand what they mean, which is to draw a line.

When in the canvas, if the mouse is pressed, we place the starting point of the canvas at the position of the mouse at this time, using moveTo(), and then when the mouse moves, use lineTo() to draw the path and stroke() To fill the path, move it and draw it, so that you can draw a curve. When the mouse is raised, we only need to cancel the mouse action. If you have seen the mouse drag effect I wrote, does it feel very weird? Like, yes, the idea is similar to drag and drop, but the specific content is different. If you haven’t seen the drag and drop effect of the mouse, you can look here

Mouse Drag

#Because the buttons below each control different things, I used a switch method to add effects to each. The canvas attribute used to set the color is strokeStyle, the method of clearing the canvas is not mentioned in the API. It may be omitted. Let’s talk about it here. The clearRect() method is used here, so let’s talk about it:

clearRect(x,y,w,h) clears the specified pixel in the given rectangle

Parameters: x,y represents the coordinates of the upper left corner of the rectangle to be cleared, w,h represents the Width and height of the cleared rectangle

Seeing this parameter, we can understand that it can clear the content of part of the canvas, or the content of the entire canvas, depending on how large an area you give. This example is Clear the entire canvas, because we need to clear the entire canvas. If you only want to clear the piece you don’t want, you can set a precise area. I won’t go into details here!

The general principle is that simple. I posted the code for your reference and understanding. By the way, I posted the effect address to experience it. Without further ado, look at the code:

css:

*{ padding:0; margin:0;}body{ background:#ccc;}canvas{ background:#fff; margin:50px 10px; }input{ display:inline-block; width:80px; height:30px; cursor:pointer; margin-left:10px;}
Copy after login


html:

 <canvas width="500" height="500" id="canvas">
        <span>亲,您的浏览器不支持canvas,换个浏览器试试吧!</span>
    </canvas>
    <p>
        <input type="button" value="红画笔" id="red">
        <input type="button" value="绿画笔" id="green">
        <input type="button" value="蓝画笔" id="blue">
        <input type="button" value="重置颜色" id="default">
        <input type="button" value="清除画布" id="clear">
    </p>
Copy after login


js:

window.onload = function(){        var canvas = document.getElementById("canvas");        var ctx = canvas.getContext("2d");        var oInput = document.getElementsByTagName("input");        for(var i=0;i<oInput.length;i++){
            oInput[i].onclick = function(){                var ID = this.getAttribute('id');                switch(ID){                    case 'red':
                        ctx.strokeStyle = 'red';                        break;                    case 'green':
                        ctx.strokeStyle = 'green';                        break;                    case 'blue':
                        ctx.strokeStyle = 'blue';                        break;                    case 'default':
                        ctx.strokeStyle = 'black';                        break;                    case 'clear':
                        ctx.clearRect(0,0,canvas.clientWidth,canvas.clientHeight);                        break;    
                }    
            }    
        }
        draw();        function draw(){
            canvas.onmousedown = function(ev){                var ev = ev || event;
                ctx.beginPath();
                ctx.moveTo(ev.clientX-canvas.offsetLeft,ev.clientY-canvas.offsetTop);
                document.onmousemove = function(ev){                    var ev = ev || event;
                    ctx.lineTo(ev.clientX - canvas.offsetLeft,ev.clientY - canvas.offsetTop);
                    ctx.stroke();    
                }
                document.onmouseup = function(ev){
                    document.onmousemove = document.onmouseup = null;
                    ctx.closePath();
                }
                
            }
        }
        
        
        
    }
Copy after login


Oh, here it is One detail I forgot to explain is that path closure must be added to the drawing part, that is, beginPath() and closePath(). Why? Because every time after the mouse is raised, when switching the following style or clearing the canvas, if the path is not closed, then the subsequent operations will pollute the previously drawn things. For example, the previous drawing was painted in red, and now I switch to green. Both the current painting and the original painting have turned green. For example, if the canvas is cleared after painting once, and then the first painting comes out again when painting again, this is not what we want, so this point needs to be Remember!

Please see here for the effect demonstration:

Small example of canvas drawing boardI will learn more about it later I bring more small examples for your reference. The writing is not very good, so I hope you don’t dislike it. I also hope that everyone will pay more attention to me. This is my biggest motivation, haha!

That’s about it, thank you everyone!

The above is the detailed content of Use canvas to design a simple drawing board. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
Which schools use canvas? Which schools use canvas? Aug 18, 2023 pm 05:59 PM

Schools using canvas include Stanford University, MIT, Columbia University, University of California, Berkeley, etc. Detailed introduction: 1. Stanford University uses Canvas as its main online learning platform. Teachers and students at Stanford University use Canvas to manage and communicate course content, and learn through functions such as online discussions, assignment submissions, and exams; 2. Ma Provincial Polytechnic Institute and MIT also use Canvas as their online learning management system and conduct course management through the Canvas platform; 3. Columbia University, etc.

Learn the canvas framework and explain the commonly used canvas framework in detail Learn the canvas framework and explain the commonly used canvas framework in detail Jan 17, 2024 am 11:03 AM

Explore the Canvas framework: To understand what are the commonly used Canvas frameworks, specific code examples are required. Introduction: Canvas is a drawing API provided in HTML5, through which we can achieve rich graphics and animation effects. In order to improve the efficiency and convenience of drawing, many developers have developed different Canvas frameworks. This article will introduce some commonly used Canvas frameworks and provide specific code examples to help readers gain a deeper understanding of how to use these frameworks. 1. EaselJS framework Ea

uniapp implements how to use canvas to draw charts and animation effects uniapp implements how to use canvas to draw charts and animation effects Oct 18, 2023 am 10:42 AM

How to use canvas to draw charts and animation effects in uniapp requires specific code examples 1. Introduction With the popularity of mobile devices, more and more applications need to display various charts and animation effects on the mobile terminal. As a cross-platform development framework based on Vue.js, uniapp provides the ability to use canvas to draw charts and animation effects. This article will introduce how uniapp uses canvas to achieve chart and animation effects, and give specific code examples. 2. canvas

What are the canvas arrow plug-ins? What are the canvas arrow plug-ins? Aug 21, 2023 pm 02:14 PM

The canvas arrow plug-ins include: 1. Fabric.js, which has a simple and easy-to-use API and can create custom arrow effects; 2. Konva.js, which provides the function of drawing arrows and can create various arrow styles; 3. Pixi.js , which provides rich graphics processing functions and can achieve various arrow effects; 4. Two.js, which can easily create and control arrow styles and animations; 5. Arrow.js, which can create various arrow effects; 6. Rough .js, you can create hand-drawn arrows, etc.

What versions of html2canvas are there? What versions of html2canvas are there? Aug 22, 2023 pm 05:58 PM

The versions of html2canvas include html2canvas v0.x, html2canvas v1.x, etc. Detailed introduction: 1. html2canvas v0.x, which is an early version of html2canvas. The latest stable version is v0.5.0-alpha1. It is a mature version that has been widely used and verified in many projects; 2. html2canvas v1.x, this is a new version of html2canvas.

What are the details of the canvas clock? What are the details of the canvas clock? Aug 21, 2023 pm 05:07 PM

The details of the canvas clock include clock appearance, tick marks, digital clock, hour, minute and second hands, center point, animation effects, other styles, etc. Detailed introduction: 1. Clock appearance, you can use Canvas to draw a circular dial as the appearance of the clock, and you can set the size, color, border and other styles of the dial; 2. Scale lines, draw scale lines on the dial to represent hours or minutes. Position; 3. Digital clock, you can draw a digital clock on the dial to indicate the current hour and minute; 4. Hour hand, minute hand, second hand, etc.

Explore the powerful role and application of canvas in game development Explore the powerful role and application of canvas in game development Jan 17, 2024 am 11:00 AM

Understand the power and application of canvas in game development Overview: With the rapid development of Internet technology, web games are becoming more and more popular among players. As an important part of web game development, canvas technology has gradually emerged in game development, showing its powerful power and application. This article will introduce the potential of canvas in game development and demonstrate its application through specific code examples. 1. Introduction to canvas technology Canvas is a new element in HTML5, which allows us to use

What properties does tkinter canvas have? What properties does tkinter canvas have? Aug 21, 2023 pm 05:46 PM

The tkinter canvas attributes include bg, bd, relief, width, height, cursor, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertwidth, selectbackground, selectforeground, xscrollcommand attributes, etc. Detailed introduction

See all articles