Home Web Front-end JS Tutorial How to use canvas to create a useful graffiti drawing board

How to use canvas to create a useful graffiti drawing board

Mar 12, 2018 pm 02:50 PM
canvas use

This time I will show you how to use canvas to make a useful graffiti drawing board. What are the precautions for using canvas to make a useful graffiti drawing board? The following is a practical case, let’s take a look. . Get the cursor coordinates in canvas

The code to get the coordinates is very simple:

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <style>
        *{margin: 0;padding: 0}    </style></head><body>
    <canvas id="board" style="border: 1px #ccc solid;"></canvas>
    <span id="point"></span>
    <script>
        var canvas = document.getElementById(&#39;board&#39;);        var context = canvas.getContext(&#39;2d&#39;);        var current = {            color: &#39;black&#39;,//<===画笔颜色配置
            width: 1//线条宽度 
        };        //获取点坐标
        function getPoint(e) {            if (e.touches && e.touches.length > 0) {                var touch = e.touches[0];                return { x: touch.pageX, y: touch.pageY };
            }            return { x: e.clientX, y: e.clientY };
        }        //鼠标移动
        function onMouseMove(e) {            var p = getPoint(e);            document.getElementById("point").innerHTML=p.x+"-"+p.y;
        }
        canvas.width = 600;
        canvas.height = 300; 
        canvas.addEventListener(&#39;mousemove&#39;, onMouseMove, false); //<==兼容PC
        canvas.addEventListener(&#39;touchmove&#39;, onMouseMove, false);//<===兼容安卓或其他系统
    </script></body></html>
Copy after login

Note: Because the events of the mouse and the touch screen are different, you can get it by just hovering the mouse over the canvas. The touch screen needs to be pressed, and the Event object returned is also different.

2. Control whether to draw

Controlling whether to draw is actually very simple. It is to control

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <style>
        *{margin: 0;padding: 0}    </style></head><body>
    <canvas id="board" style="border: 1px #ccc solid;"></canvas>
    <span id="point"></span>
    <script>
        var canvas = document.getElementById(&#39;board&#39;);        var context = canvas.getContext(&#39;2d&#39;);        var current = {            color: &#39;black&#39;,//<===画笔颜色配置
            width: 1//线条宽度 
        };        var drawing = false;//<===是否绘制
        //获取点坐标
        function getPoint(e) {            if (e.touches && e.touches.length > 0) {                var touch = e.touches[0];                return { x: touch.pageX, y: touch.pageY };
            }            return { x: e.clientX, y: e.clientY };
        }         //鼠标按下
         function onMouseDown(e) {
                drawing = true; 
            }            //鼠标弹起
            function onMouseUp(e) {                if (!drawing) { return; }
                drawing = false; 
            }        //鼠标移动
        function onMouseMove(e) {            if (!drawing) { return; }            var p = getPoint(e);            document.getElementById("point").innerHTML=p.x+"-"+p.y;
        }
        canvas.width = 600;
        canvas.height = 300; 
        canvas.addEventListener(&#39;mousedown&#39;, onMouseDown, false);
        canvas.addEventListener(&#39;mouseup&#39;, onMouseUp, false);
        canvas.addEventListener(&#39;mouseout&#39;, onMouseUp, false);
        canvas.addEventListener(&#39;mousemove&#39;, onMouseMove, false);
        canvas.addEventListener(&#39;touchstart&#39;, onMouseDown, false);
        canvas.addEventListener(&#39;touchend&#39;, onMouseUp, false);
        canvas.addEventListener(&#39;touchmove&#39;, onMouseMove, false);    </script></body></html>
Copy after login
## by judging the value of the self-defined variabledrawing during different events. #3. Line drawing

The code for line drawing is also very simple

....//线条绘制function drawLine(x0, y0, x1, y1, color, width) {
    context.beginPath();
    context.moveTo(x0, y0);
    context.lineTo(x1, y1);
    context.strokeStyle = color;
    context.lineWidth = width; 
    context.stroke();
    context.closePath();
}
....
Copy after login

Integrate the line drawing code into the event:

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title></head><body>
    <canvas id="board" style="border: 1px #ccc solid;"></canvas>
    <span id="point"></span>
    <script>
        var canvas = document.getElementById(&#39;board&#39;);        var context = canvas.getContext(&#39;2d&#39;);        var current = {            color: &#39;black&#39;,//<===画笔颜色配置
            width: 1//线条宽度 
        };        var drawing = false;//<===是否绘制
        //获取点坐标
        function getPoint(e) {            if (e.touches && e.touches.length > 0) {                var touch = e.touches[0];                return { x: touch.pageX, y: touch.pageY };
            }            return { x: e.clientX, y: e.clientY };
        }        //线条绘制
        function drawLine(x0, y0, x1, y1, color, width) {
            context.beginPath();
            context.moveTo(x0, y0);
            context.lineTo(x1, y1);
            context.strokeStyle = color;
            context.lineWidth = width; 
            context.stroke();
            context.closePath();
        }        //鼠标按下
        function onMouseDown(e) {
            drawing = true;            //记录按下点
            var p = getPoint(e);
            current.x = p.x;
            current.y = p.y;
        }        //鼠标弹起
        function onMouseUp(e) {            if (!drawing) { return; }
            drawing = false;            //绘制结束点
            var p = getPoint(e);
            drawLine(current.x, current.y, p.x, p.y, current.color, current.width);
        }        //鼠标移动
        function onMouseMove(e) {            if (!drawing) { return; }            var p = getPoint(e);            document.getElementById("point").innerHTML = p.x + "-" + p.y;            //移动绘制
            drawLine(current.x, current.y, p.x, p.y, current.color, current.width);
            current.x = p.x;
            current.y = p.y;
        }
        canvas.width = 600;
        canvas.height = 300;
        canvas.addEventListener(&#39;mousedown&#39;, onMouseDown, false);
        canvas.addEventListener(&#39;mouseup&#39;, onMouseUp, false);
        canvas.addEventListener(&#39;mouseout&#39;, onMouseUp, false);
        canvas.addEventListener(&#39;mousemove&#39;, onMouseMove, false);
        canvas.addEventListener(&#39;touchstart&#39;, onMouseDown, false);
        canvas.addEventListener(&#39;touchend&#39;, onMouseUp, false);
        canvas.addEventListener(&#39;touchmove&#39;, onMouseMove, false);    </script></body></html>
Copy after login

4. Line drawing optimization

It's fine when the width of the drawn line is relatively small, but once it is thicker, there will be writing problems:

At this time, just slightly change the drawing code

....//线条绘制function drawLine(x0, y0, x1, y1, color, width) {
    context.beginPath();
    context.moveTo(x0, y0);
    context.lineTo(x1, y1);
    context.strokeStyle = color;
    context.lineWidth = width; 
    //-----加入-----
    context.lineCap = "round";
    context.lineJoin = "round";    //-----加入-----
    context.stroke();
    context.closePath();
}
....
Copy after login

I believe I read it You have mastered the method in the case of this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Related reading:

How to use s-xlsx to merge cells


js-xlsx reads xlsx files Detailed explanation of asynchronous


How to use s-xlsx to import and export Excel files (Part 2)

The above is the detailed content of How to use canvas to create a useful graffiti 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 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
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
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.

Which computer should Geographic Information Science majors choose? Which computer should Geographic Information Science majors choose? Jan 13, 2024 am 08:00 AM

Recommended computers suitable for students majoring in geographic information science 1. Recommendation 2. Students majoring in geographic information science need to process large amounts of geographic data and conduct complex geographic information analysis, so they need a computer with strong performance. A computer with high configuration can provide faster processing speed and larger storage space, and can better meet professional needs. 3. It is recommended to choose a computer equipped with a high-performance processor and large-capacity memory, which can improve the efficiency of data processing and analysis. In addition, choosing a computer with larger storage space and a high-resolution display can better display geographic data and results. In addition, considering that students majoring in geographic information science may need to develop and program geographic information system (GIS) software, choose a computer with better graphics processing support.

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

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.

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 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