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

Detailed graphic explanation of how to clear the keep-alive cache

Table of contents Opening scene Direct rendering ...

How to quickly build your own server detailed tutorial (Java environment)

1. Purchase of Server 1. I chose Alibaba Cloud...

How to solve the error of PyCurl under Linux

Solution to "Could not run curl-config"...

How to use React to implement image recognition app

Let me show you the effect picture first. Persona...

How to use CSS to achieve data hotspot effect

The effect is as follows: analyze 1. Here you can...

Talking about Less and More in Web Design (Picture)

Less is More is a catchphrase for many designers....

A brief discussion on logic extraction and field display of Vue3 in projects

Table of contents Logical Layering Separate busin...

Detailed explanation of how Vue components transfer values ​​to each other

Table of contents Overview 1. Parent component pa...

How to write HTML head in mobile device web development

Copy code The code is as follows: <head> &l...

Detailed explanation of the use of Linux seq command

01. Command Overview The seq command is used to g...