Canvas allows you to draw sample code for an derailed trace by pressing the mouse. canvas sample code

Source: Internet
Author: User

Canvas allows you to draw sample code for an derailed trace by pressing the mouse. canvas sample code

Summary

I have written vue, react, regular expressions, algorithms, mini programs, and other knowledge since my work, but I have never written canvas, because I really can't!

In 2018, I set a small goal for myself: to learn canvas, the effect is to use canvas to implement some animations that are not easily implemented by css3.

As the first result of studying canvas, many people are learning canvas's first demo to implement a "Clock". Of course, I have also implemented one, but I will not talk about it, it is about something more interesting and simple.

Draw tracks with mouse hold

Requirement

On a canvas, there is no canvas in the initial state. Now, I want to add a mouse event to the canvas and write it with the mouse. The specific effect is to move the mouse to any point on the canvas, then press and hold the mouse, move the mouse to start writing!

Principle

First, we need a canvas, calculate the location of the mouse on the canvas, bind the onmousedown event and onmousemove event to the mouse, and draw a path during the movement, when you release the mouse, the painting ends.

This idea is simple, but some of it requires tips.

1. an html file containing the canvas element is required.

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

<! Doctype html> 

2. Determine whether the current environment supports canvas.

In main. js, we write a self-executed function. The following is a code snippet of compatibility judgment. The "Code subject" will be the core of the implementation requirement.

(Function () {let theCanvas = document. querySelector ('# theCanvas') if (! TheCanvas |! TheCanvas. getContext) {// incompatible canvas return false} else {// code body }})()

3. obtain 2d objects.

let context = theCanvas.getContext('2d')

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

Why is it necessary to obtain the coordinates? By default, the mouse obtains the relative coordinates of the current window, while the canvas can be located at any position on the page. Therefore, you need to calculate the actual mouse coordinates.

Encapsulate the real coordinates of the mouse over the canvas into a function. If you think it is abstract, you can draw a picture on the draft to understand why this operation is necessary.

Generally, 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 indicates to determine the scaling behavior in the canvas and find the scaling multiple.

Const windowToCanvas = (canvas, x, y) => {// obtain some attributes of the canvas Element's distance from the window. On the MDN, let rect = canvas. the getBoundingClientRect () // x and y parameters respectively specify the coordinates between the mouse and the window, and then subtract the distance between the canvas and the left and top of the window. Return {x: x-rect. left * (canvas. width/rect. width), y: y-rect. top * (canvas. height/rect. height )}}

5. With the 4th-step tool function, we can add a mouse event to the canvas!

Bind the mouse to the onmousedown event and use moveTo to draw the coordinate start point.

TheCanvas. onmousedown = function (e) {// obtain the coordinates of the Point pressed by the mouse relative to the canvas. Let ele = windowToCanvas (theCanvas, e. clientX, e. clientY) // deconstruct assignment of es6 let {x, y} = ele // draw the start point. Context. moveTo (x, y )}

6. How should I listen when I move the mouse without a long mouse?

The trick here is to execute an onmousemove event inside onmousedown, so that you can listen and hold the mouse and move it.

TheCanvas. onmousedown = function (e) {// obtain the coordinates of the Point pressed by the mouse relative to the canvas. Let ele = windowToCanvas (theCanvas, e. clientX, e. clientY) // deconstruct assignment of es6 let {x, y} = ele // draw the start point. Context. moveTo (x, y) // theCanvas of the mouse movement event. onmousemove = (e) => {// obtain the new coordinate position when moving, and use lineTo to record the current coordinate, then stroke draws the path from the previous point to the current point, let ele = windowToCanvas (theCanvas, e. clientX, e. clientY) let {x, y} = ele context. lineTo (x, y) context. stroke ()}}

7. When the mouse is released, no path is drawn.

Is there any way to let the onmouseup event stop the two events listened on above? There are many ways to set onmousedown and onmousemove to null. Here I use the "Switch ". IsAllowDrawLine is set to the bool value to control whether the function is executed. For specific code, see the complete source code below.

Source code

Divided into 3 files, index.html, main. js, utils. js, es6 syntax is used here. I configured the development environment using parcle, so no error is reported. If you copy the Code directly, an error occurs during running, if you cannot upgrade your browser, you can change the es6 syntax to es5.

1、index.html

As shown above, we will not repeat it.

2. main. js

import { windowToCanvas } from './utils'(function() {    let theCanvas = document.querySelector('#theCanvas')    if (!theCanvas || !theCanvas.getContext) {        return false    } else {        let context = theCanvas.getContext('2d')        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

/** Get the coordinates of the mouse over the 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

Here is a misunderstanding. I used the canvas object to bind theCanvas. onmouseup event. In fact, canvas cannot bind events, but the document and window events are actually bound. However, because the browser will automatically help you determine and handle the event, you don't have to worry about it.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.