国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Get the mouse position on canvas
Determine whether the mouse clicks a graphic
Realize hover effects or real-time feedback
Tips and precautions
Home Web Front-end H5 Tutorial How to handle mouse events on a canvas?

How to handle mouse events on a canvas?

Jun 26, 2025 am 01:00 AM
canvas mouse events

To handle mouse events on canvas, you need to manually monitor and judge the trigger area in combination with coordinates. 1. When obtaining the mouse position, you need to convert clientX and clientY to the internal coordinates of canvas. The formula is x = e.clientX - rect.left, y = e.clientY - rect.top; 2. If there is a zoom or transform style, the coordinates need to be adjusted accordingly; 3. To determine whether to click on a graphic, you need to pre-record the graphic information and detect whether the coordinates fall in the corresponding area when clicking; 4. To realize the hover effect, you can listen to mousemove and clear and redraw canvas or use double buffering technology; 5. Note that the mobile terminal needs to use touch events to replace hover, and the performance optimization and scaling adaptation issues must be considered.

Handling mouse events on canvas is not complicated, but several key points need to be understood. Canvas itself is just a bitmap canvas, which does not have the ability to interact like DOM elements. Therefore, to make canvas respond to mouse clicks, hovering and other behaviors, you need to manually monitor the event and judge the trigger area based on the coordinates.

Get the mouse position on canvas

clientX and clientY in the mouse event object provided by the browser are the coordinates relative to the viewport, and what you need to judge is the specific position inside canvas, so a conversion is required.

 const canvas = document.getElementById('myCanvas');
const rect = canvas.getBoundingClientRect();

canvas.addEventListener('mousedown', (e) => {
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;
  console.log(`Mouse click location: x=${x}, y=${y}`);
});

A few points to note:

  • If canvas has a scale or transform style, such as scale() in CSS, the coordinates need to be adjusted accordingly.
  • Touch events on mobile terminals need to be processed separately and can be simulated by touchstart and other events.

Determine whether the mouse clicks a graphic

Since canvas does not have the built-in "click on a certain graphic" function, you need to record the information of the drawn content (such as position and shape) by yourself, and then judge whether it falls in the area based on the mouse coordinates.

Take rectangles as an example:

 const rectData = { x: 50, y: 50, width: 100, height: 100 };

canvas.addEventListener('mousedown', (e) => {
  const mouseX = e.clientX - rect.left;
  const mouseY = e.clientY - rect.top;

  if (
    mouseX >= rectData.x &&
    mouseX <= rectData.x rectData.width &&
    mouseY >= rectData.y &&
    mouseY <= rectData.y rectData.height
  ) {
    console.log(&#39;Clicked on the rectangle&#39;);
  }
});

If you have drawn multiple graphics, it is recommended to maintain a graphics list, and each graphics saves its boundary information or path, so that you can traverse and judge each time you click.

Realize hover effects or real-time feedback

The key to implementing hover is to listen to mousemove events and continuously detect whether the current mouse position is in the target area.

you can:

  • Clear canvas and repaint each time you move (suitable for simple scenes)
  • Or use double buffering technology to draw the state change part on off-screen canvas (suitable for complex scenarios)

The example logic is as follows:

 canvas.addEventListener(&#39;mousemove&#39;, (e) => {
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;

  // Clear the previous draw ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Re-draw all graphics drawAllShapes();

  // If the mouse is on the graph, add highlight if (isMouseOverShape(x, y)) {
    drawHighlight();
  }
});

Although this method is not as efficient as DOM, it is sufficient when there are not many graphics.

Tips and precautions

  • Keep the graphic data structure clear : Don’t just rely on images to judge interactions, you should use data to record graphic information.
  • Performance optimization : If there are many graphics and frequent redrawing will affect performance, you can consider local updates or use offscreen canvas.
  • Compatibility issue : There is no hover on the mobile side, so touch-related events should be replaced.
  • Zoom adaptation : If the page uses a high-definition solution (such as rem, dpr), remember to process the size of the canvas as well.

Basically that's it. Although canvas does not naturally support interaction like HTML elements, as long as you master coordinate mapping and graphical judgment methods, you can flexibly implement various mouse response functions.

The above is the detailed content of How to handle mouse events on a canvas?. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Learn to use Vue's v-on instruction to handle mouse move-in and move-out events Learn to use Vue's v-on instruction to handle mouse move-in and move-out events Sep 15, 2023 am 08:34 AM

Learn to use Vue's v-on instruction to handle mouse move-in and move-out events. Mouse move-in and move-out events are one of the common interactive effects in Web pages. Vue provides the v-on instruction to handle these events conveniently. This article will introduce how to use Vue's v-on directive to handle mouse move-in and move-out events, and provide specific code examples. Before using Vue's v-on directive to handle mouse move-in and move-out events, we need to understand the basic usage of the v-on directive. The v-on directive is used to listen to DOM events and

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

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