search
HomeWeb Front-endH5 TutorialHow to use canvas to draw a trajectory by holding down the mouse and moving it

This article mainly introduces the sample code for using canvas to draw a trajectory by holding down the mouse and moving it. The content is quite good. I will share it with you now and give it as a reference.

Summary

Since I started working, I have written about vue, react, regular rules, algorithms, small programs, etc., but I have never written about canvas, because I really don’t know how!

In 2018, set a small goal for yourself: learn canvas, and the effect achieved is to be able to use canvas to realize some animations that are not easy to achieve with CSS3.

This article is the first gain from learning canvas. The first demo that many people do when learning canvas is to implement a "clock". Of course, I also implemented one, but instead of talking about this, I will talk about it. A more interesting and simpler thing.

Hold down the mouse to draw the track

Requirements

On a canvas canvas, the initial state of the canvas has nothing No, now, I want to add some mouse events to the canvas and use the mouse to write on the canvas. The specific effect is to move the mouse to any point on the canvas, then hold down the mouse, move the mouse position, and you can start writing!

Principle

Let’s briefly analyze the idea. First, we need a canvas, and then calculate the position of the mouse on the canvas. Bind the onmousedown event and onmousemove event to the mouse, and draw the path during the movement. When the mouse is released, the drawing ends.

Although this idea is very simple, there are some parts that require some tricks to implement.

1. An html file is required, containing canvas elements.

This is a canvas with a width of 800 and a height of 400. Why didn't you write px? Oh, I don’t understand it yet, it’s recommended by the canvas document.

<!doctype html>
<html class="no-js" lang="zh">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>canvas学习</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="manifest" href="site.webmanifest">
        <link rel="apple-touch-icon" href="icon.png">
        <link rel="stylesheet" href="css/main.css">
    </head>
    <body>
        <canvas id="theCanvas" width="800" height="400"></canvas>
        <script src="js/main.js"></script>
    </body>
</html>

2. Determine whether the current environment supports canvas.

In main.js, we write a self-executing function. The following is the code snippet for compatibility judgment. The "code body" will be the core of the implementation requirements.

(function() {
    let theCanvas = document.querySelector(&#39;#theCanvas&#39;)
    if (!theCanvas || !theCanvas.getContext) {
        //不兼容canvas
        return false
    } else {
        //代码主体
    }
})()

3. Get the 2d object.

let context = theCanvas.getContext(&#39;2d&#39;)

4. Get the coordinates of the current mouse relative to the canvas.

Why do we need to obtain this coordinate? Because the mouse defaults to obtaining the relative coordinates of the current window, and the canvas can be located anywhere on the page, calculations are required to obtain the real mouse coordinates.

Encapsulates the acquisition of the real coordinates of the mouse relative to the canvas into a function. If you feel abstract, you can draw a picture on a scratch paper to understand why this operation is required.

Normally, it can be x - rect.left and y - rect.top. But why is it actually x - rect.left * (canvas.width/rect.width)?

canvas.width/rect.width means to determine the scaling behavior in canvas and find the scaling multiple.

const windowToCanvas = (canvas, x, y) => {
    //获取canvas元素距离窗口的一些属性,MDN上有解释
    let rect = canvas.getBoundingClientRect()
    //x和y参数分别传入的是鼠标距离窗口的坐标,然后减去canvas距离窗口左边和顶部的距离。
    return {
        x: x - rect.left * (canvas.width/rect.width),
        y: y - rect.top * (canvas.height/rect.height)
    }
}

5. With the tool function in step 4, we can add mouse events to the canvas!

First bind the onmousedown event to the mouse, and use moveTo to draw the starting point of the coordinates.

theCanvas.onmousedown = function(e) {
    //获得鼠标按下的点相对canvas的坐标。
    let ele = windowToCanvas(theCanvas, e.clientX, e.clientY)
    //es6的解构赋值
    let { x, y } = ele
    //绘制起点。
    context.moveTo(x, y)
}

6. When moving the mouse, there is no mouse long press event, how should I monitor it?

The little trick used here is to execute an onmousemove (mouse movement) event inside onmousedown, so that the mouse can be monitored and moved.

theCanvas.onmousedown = function(e) {
    //获得鼠标按下的点相对canvas的坐标。
    let ele = windowToCanvas(theCanvas, e.clientX, e.clientY)
    //es6的解构赋值
    let { x, y } = ele
    //绘制起点。
    context.moveTo(x, y)
    //鼠标移动事件
    theCanvas.onmousemove = (e) => {
        //移动时获取新的坐标位置,用lineTo记录当前的坐标,然后stroke绘制上一个点到当前点的路径
        let ele = windowToCanvas(theCanvas, e.clientX, e.clientY)
        let { x, y } = ele
        context.lineTo(x, y)
        context.stroke()
    }
}

7. When the mouse is released, the path will no longer be drawn.

Is there any way to prevent the two events monitored above in the onmouseup event? There are many methods. Setting onmousedown and onmousemove to null is one. I used "switch" here. isAllowDrawLine is set to a bool value to control whether the function is executed. For the specific code, please see the complete source code below.

Source code

is divided into 3 files, index.html, main.js, utils.js. The es6 syntax is used here. I configured it using parcle. The development environment is installed, so there will be no errors. If you copy the code directly and an error occurs when running, if the browser cannot be upgraded, you can change the es6 syntax to es5.

1, index.html

It has been shown above and will not be repeated again.

2、main.js

import { windowToCanvas } from './utils'
(function() {
    let theCanvas = document.querySelector('#theCanvas')
    if (!theCanvas || !theCanvas.getContext) {
        return false
    } else {
        let context = theCanvas.getContext(&#39;2d&#39;)
        let isAllowDrawLine = false
        theCanvas.onmousedown = function(e) {
            isAllowDrawLine = true
            let ele = windowToCanvas(theCanvas, e.clientX, e.clientY)
            let { x, y } = ele
            context.moveTo(x, y)
            theCanvas.onmousemove = (e) => {
                if (isAllowDrawLine) {
                    let ele = windowToCanvas(theCanvas, e.clientX, e.clientY)
                    let { x, y } = ele
                    context.lineTo(x, y)
                    context.stroke()
                }
            }
        }
        theCanvas.onmouseup = function() {
            isAllowDrawLine = false
        }
    }
})()

3、utils.js

/*
* 获取鼠标在canvas上的坐标
* */
const windowToCanvas = (canvas, x, y) => {
    let rect = canvas.getBoundingClientRect()
    return {
        x: x - rect.left * (canvas.width/rect.width),
        y: y - rect.top * (canvas.height/rect.height)
    }
}

export {
    windowToCanvas
}

Summary

There is a misunderstanding here. I use the canvas object to bind the event theCanvas.onmouseup. In fact, canvas cannot bind events. What is really bound is document and window. . But since the browser will automatically judge it for you and hand over event processing, there is no need to worry at all.

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Use HTML5 How to draw polygons such as triangles and rectangles with Canvas

The above is the detailed content of How to use canvas to draw a trajectory by holding down the mouse and moving it. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

The Legacy of HTML5: Understanding H5 in the PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5 Code: Accessibility and Semantic HTMLH5 Code: Accessibility and Semantic HTMLApr 09, 2025 am 12:05 AM

H5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.

Is h5 same as HTML5?Is h5 same as HTML5?Apr 08, 2025 am 12:16 AM

"h5" and "HTML5" are the same in most cases, but they may have different meanings in certain specific scenarios. 1. "HTML5" is a W3C-defined standard that contains new tags and APIs. 2. "h5" is usually the abbreviation of HTML5, but in mobile development, it may refer to a framework based on HTML5. Understanding these differences helps to use these terms accurately in your project.

What is the function of H5?What is the function of H5?Apr 07, 2025 am 12:10 AM

H5, or HTML5, is the fifth version of HTML. It provides developers with a stronger tool set, making it easier to create complex web applications. The core functions of H5 include: 1) elements that allow drawing graphics and animations on web pages; 2) semantic tags such as, etc. to make the web page structure clear and conducive to SEO optimization; 3) new APIs such as GeolocationAPI support location-based services; 4) Cross-browser compatibility needs to be ensured through compatibility testing and Polyfill library.

How to do h5 linkHow to do h5 linkApr 06, 2025 pm 12:39 PM

How to create an H5 link? Determine the link target: Get the URL of the H5 page or application. Create HTML anchors: Use the <a> tag to create an anchor and specify the link target URL. Set link properties (optional): Set target, title, and onclick properties as needed. Add to webpage: Add HTML anchor code to the webpage where you want the link to appear.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.