Two ways to implement HTML to randomly drag content positions

Two ways to implement HTML to randomly drag content positions

Test: Chrome v80.0.3987.122 is normal

There are two ways: drag the normal label position or drag the text box position in the canvas

1. Realize the mouse drag label element to any position

Demo address

CSS Code

#range {
    position: relative;
    width: 600px;
    height: 400px;
    margin: 10px;
    background-color: rgb(133, 246, 250);
}

.icon {
    position: absolute;
    height: 100px;
    width: 100px;
    cursor: move;
    background-color: #ff9204;
    user-select: none;
}

HTML code

<div id="range">
    <div class="icon">100*100</div>
</div>

js code

const main = document.getElementById('range');
const icon = document.querySelector('.icon');
let move = false;
let deltaLeft = 0, deltaTop = 0;

// Drag start event, to be bound to the moved element icon.addEventListener('mousedown', function (e) {
    /*
    * @des deltaLeft is the value that remains unchanged during the movement*/
    deltaLeft = e.clientX-e.target.offsetLeft;
    deltaTop = e.clientY-e.target.offsetTop;
    move = true;
})

// The mobile trigger event should be placed on the area control element main.addEventListener('mousemove', function (e) {
    if (move) {
        const cx = e.clientX;
        const cy = e.clientY;
        /** Subtract to get the position relative to the parent element*/   
        let dx = cx - deltaLeft
        let dy = cy - deltaTop

        /** Prevent exceeding the parent element range */
        if (dx < 0) dx = 0
        if (dy < 0) dy = 0
        if (dx > 500) dx = 500
        if (dy > 300) dy = 300
        icon.setAttribute('style', `left:${dx}px;top:${dy}px`)
    }
})

// The drag end trigger should be placed on the area control element main.addEventListener('mouseup', function (e) {
    move = false;
    console.log('mouseup');
})

2. Draw a text box on canvas and drag it to any position with the mouse

CSS Code

.cus-canvas{
    background: rgb(50, 204, 243);
}

.input-ele{
    display: none;
    position: fixed;
    width: 180px;
    border: 0;
    background-color: #fff;
}

HTML code

<div>
    <canvas id="canvas" class="cus-canvas" width="800" height="600"></canvas>
    <input id="inputEle" class="input-ele"/>
</div>

js code

The implementation principle is to record the position of the mouse movement and continuously redraw the rectangle and text content

let mouseDown = false;
let deltaX = 0;
let deltaY = 0;
let text = 'hello'
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const cw = canvas.width, ch = canvas.height;
const rect = {
    x: 20,
    y: 20,
    width: 150,
    height: 50
}

/** Set text and border styles */
ctx.font="16px Arial";
ctx.fillStyle = "#fff"; 
/** When set to center, the center of the text segment will be at the x point of fillText*/
ctx.textAlign = 'center';
ctx.lineWidth = '2';
ctx.strokeStyle = '#fff';

strokeRect()

const inputEle = document.getElementById('inputEle');
inputEle.onkeyup = function(e) {
    if(e.keyCode === 13) {
        text = inputEle.value
        strokeRect()
        inputEle.setAttribute('style', `display:none`)
    }
}

canvas.ondblclick = function(e){ 
    inputEle.setAttribute('style', `left:${e.clientX}px;top:${e.clientY}px;display:block`);
    inputEle.focus();
}

canvas.onmousedown = function(e){ 
    /** Get the distance between the left border of the viewport and the left border of the canvas plus the length between the mouse click position and the left border of the canvas. This value is the constant value during relative movement*/
    deltaX = e.clientX - rect.x;
    deltaY=e.clientY - rect.y;
    mouseDown = true
};  

const judgeW = cw-rect.width, judgeH = ch-rect.height;

canvas.onmousemove = function(e){ 
    if(mouseDown) {
        /** Subtract to get the length between the left border of the rectangle and the left border of the canvas*/
        let dx = e.clientX-deltaX; 
        let dy = e.clientY-deltaY; 
        if(dx < 0) {
            dx = 0;
        } else if (dx > judgeW) {
            dx = judgeW;
        }
        if(dy < 0) {
            dy = 0;
        } else if(dy > judgeH) {
            dy = judgeH;
        }
        rect.x = dx;
        rect.y = dy; 
        strokeRect()
    }
};  
canvas.onmouseup = function(e){ 
    mouseDown = false
};  

/** Clear the specified area */
function clearRect() {
    ctx.clearRect(0, 0, cw, ch)
}

/** Draw a rectangle */
function strokeRect() {
    clearRect()

    /** If beginPath is not called here, the history rectangle will be redrawn*/
    ctx.beginPath() 
    ctx.rect(rect.x, rect.y, rect.width, rect.height)
    ctx.stroke();
    // Set the font content and its position on the canvas ctx.fillText(text, rect.x + 70, rect.y + 30);
}

Welcome to Github

This concludes this article on two ways to implement arbitrary dragging of content in HTML. For more relevant content on arbitrary dragging of content in HTML, please search previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

<<:  Node.js solves the problem of Chinese garbled characters in client request data

>>:  MySQL import and export backup details

Recommend

Implementation of Vue package size optimization (from 1.72M to 94K)

1. Background I recently made a website, uidea, w...

MySQL compression usage scenarios and solutions

Introduction Describes the use cases and solution...

Teach you how to use Portainer to manage multiple Docker container environments

Table of contents Portainer manages multiple Dock...

Use CSS content attr to achieve mouse hover prompt (tooltip) effect

Why do we achieve this effect? ​​In fact, this ef...

Vue implements calling PC camera to take photos in real time

Vue calls the PC camera to take pictures in real ...

Detailed explanation of importing/exporting MySQL data in Docker container

Preface We all know that the import and export of...

Nginx load balancing algorithm and failover analysis

Overview Nginx load balancing provides upstream s...

HTML table only displays the outer border of the table

I would like to ask a question. In Dreamweaver, I...

A little-known JS problem: [] == ![] is true, but {} == !{} is false

console.log( [] == ![] ) // true console.log( {} ...

When you enter a URL, what exactly happens in the background?

As a software developer, you must have a complete...

Detailed explanation of MySQL date string timestamp conversion

The conversion between time, string and timestamp...

Web Design Tutorial (5): Web Visual Design

<br />Previous article: Web Design Tutorial ...