


Learn how to implement the canvas drag function in the mini program through an example
Nov 29, 2021 pm 07:23 PMThis article will explain how to implement the canvas drag element function of the WeChat applet through code examples. I hope it will be helpful to everyone!
<canvas type="2d" id="myCanvas" style="max-width:90%"></canvas>
data data// 鼠標(biāo)狀態(tài) statusConfig : { idle: 0, //正常狀態(tài) Drag_start: 1, //拖拽開始 Dragging: 2, //拖拽中 }, // canvas 狀態(tài) canvasInfo : { // 圓的狀態(tài) status: 0, // 鼠標(biāo)在在圓圈里位置放里頭 dragTarget: null, // 點(diǎn)擊圓時(shí)的的位置 lastEvtPos: {x: null, y: null}, },Draw two circles on the canvas
onLoad: function (options) { // 設(shè)置畫布,獲得畫布的上下文 ctx this.getCanvas(); }, getCanvas(){ // 根據(jù)id獲取canvas元素,微信小程序無(wú)法使用document, 我們需要使用wx.createSelectorQuery()來(lái)代替 const query = wx.createSelectorQuery() query.select('#myCanvas') .fields({ node: true, size: true }) .exec((res) => { const canvas = res[0].node // 設(shè)置畫布的比例 canvas.width="500"; canvas.height="600"; const ctx = canvas.getContext('2d') // 在畫布上畫兩個(gè)圓,將ctx傳遞過(guò)去繪畫 this.drawCircle(ctx, 100, 100, 20); this.drawCircle(ctx, 200, 200, 10); // 將我們繪畫的信息保存起來(lái),之后移動(dòng)后需要清空畫板重新畫 var circles = [] circles.push({x: 100, y: 100, r: 20}); circles.push({x: 200, y: 200, r: 10}); // 不要忘記保存哦 this.setData({ circles }) }) }, // 畫圓 drawCircle(ctx, cx, cy, r){ ctx.save() ctx.beginPath() ctx.strokeStyle = 'yellow' ctx.lineWidth = 3 ctx.arc(cx, cy, r, 0, 2 * Math.PI) ctx.stroke() ctx.closePath() ctx.restore() },
<canvas type="2d" id="myCanvas"
bindtouchstart="handleCanvasStart" bindtouchmove="handleCanvasMove" bindtouchend="handleCanvasEnd"
style="height: 600px; width: 500px;">
</canvas>
Trigger conditions | |
---|---|
Finger touch action starts | |
Finger moves after touching | |
The finger touch action is interrupted, such as an incoming call reminder, pop-up window | |
The finger touch action ends | |
Leave immediately after touching the finger |
handleCanvasStart(e){ // 獲取點(diǎn)擊點(diǎn)的位置 const canvasPosition = this.getCanvasPosition(e); // 判斷點(diǎn)擊點(diǎn)的位置在不在圈里,如果不在返回false, 在返回圓的信息 const circleRef = this.ifInCircle(canvasPosition); const {canvasInfo, statusConfig} = this.data; // 在圓里的話,改變圓此時(shí)的狀態(tài)信息 if(circleRef){ canvasInfo.dragTarget = circleRef; //改變拖動(dòng)狀態(tài) idle -> Drag_start canvasInfo.status = statusConfig.Drag_start; canvasInfo.lastEvtPos = canvasPosition; } this.setData({ canvasInfo }) }, // 獲取點(diǎn)擊點(diǎn)的位置 getCanvasPosition(e){ return{ x: e.changedTouches[0].x, y: e.changedTouches[0].y } }, // 看點(diǎn)擊點(diǎn)擊點(diǎn)是不是在圈里 ifInCircle(pos){ const {circles} = this.data; for( let i = 0 ; i < circles.length; i++ ){ // 判斷點(diǎn)擊點(diǎn)到圓心是不是小于半徑 if( this.getDistance(circles[i], pos) < circles[i].r ){ return circles[i] } } return false }, // 獲取兩點(diǎn)之間的距離(數(shù)學(xué)公式) getDistance(p1, p2){ return Math.sqrt((p1.x-p2.x) ** 2 + (p1.y-p2.y) ** 2) }
Move after touching the finger, redraw the circle
handleCanvasMove(e){ const canvasPosition = this.getCanvasPosition(e); const {canvasInfo, statusConfig, circles} = this.data; // 是拖拽開始狀態(tài),滑動(dòng)的大小大于5(防抖) if( canvasInfo.status === statusConfig.Drag_start && this.getDistance(canvasPosition, canvasInfo.lastEvtPos) > 5){ // 改變拖動(dòng)狀態(tài) Drag_start -> Dragging canvasInfo.status = statusConfig.Dragging; }else if( canvasInfo.status === statusConfig.Dragging ){ canvasInfo.dragTarget.x = canvasPosition.x; canvasInfo.dragTarget.y = canvasPosition.y; // 重新繪制 const query = wx.createSelectorQuery() query.select('#myCanvas') .fields({ node: true, size: true }) .exec((res) => { const canvas = res[0].node canvas.width="500"; canvas.height="600"; const ctx = canvas.getContext('2d') // 遍歷circles,把圓重新畫一遍 circles.forEach(c => this.drawCircle(ctx, c.x, c.y, c.r)) }) } this.setData({ canvasInfo, }) }
The finger touch action ends, change the canvasInfo state to idle again
handleCanvasEnd(e){ const {canvasInfo, statusConfig} = this.data; if( canvasInfo.status === statusConfig.Dragging ){ // 改變拖動(dòng)狀態(tài) Dragging -> idle canvasInfo.status = statusConfig.idle; this.setData({ canvasInfo }) } }
Learn from the bosses of Bilibili, but the gap between WeChat mini program and html canvas has already made me depressed
[Related learning recommendations:
小program development tutorialThe above is the detailed content of Learn how to implement the canvas drag function in the mini program through an example. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: <!--index.wxml-->&l

According to news from this site on October 31, on May 27 this year, Ant Group announced the launch of the "Chinese Character Picking Project", and recently ushered in new progress: Alipay launched the "Chinese Character Picking-Uncommon Characters" mini program to collect collections from the society Rare characters supplement the rare character library and provide different input experiences for rare characters to help improve the rare character input method in Alipay. Currently, users can enter the "Uncommon Characters" applet by searching for keywords such as "Chinese character pick-up" and "rare characters". In the mini program, users can submit pictures of rare characters that have not been recognized and entered by the system. After confirmation, Alipay engineers will make additional entries into the font library. This website noticed that users can also experience the latest word-splitting input method in the mini program. This input method is designed for rare words with unclear pronunciation. User dismantling

How uniapp can achieve rapid conversion between mini programs and H5 requires specific code examples. In recent years, with the development of the mobile Internet and the popularity of smartphones, mini programs and H5 have become indispensable application forms. As a cross-platform development framework, uniapp can quickly realize the conversion between small programs and H5 based on a set of codes, greatly improving development efficiency. This article will introduce how uniapp can achieve rapid conversion between mini programs and H5, and give specific code examples. 1. Introduction to uniapp unia

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

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

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.

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

How to achieve the left and right drag switching effect of images with JavaScript? In modern web design, dynamic effects can increase user experience and visual appeal. The left and right drag switching effect of pictures is a common dynamic effect, which allows users to switch different content by dragging pictures. In this article, we will introduce how to use JavaScript to achieve this image switching effect and provide specific code examples. First, we need to prepare some HTML and CSS code to create an image containing multiple images
