JSFiddle - React, Tailwind, and code Playground
by HappyAcorn77
HTML
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h4>Drag the texts</h4>
<canvas id="canvas" width=300 height=300></canvas>
<!--
<div>
Wait for image to load and use <b>left click</b> drag to pan, and
<b>mouse wheel</b> to zoom in and out. <b>Right click</b> to return to
home scale and pan. Image is 4000 by 2000 plus so give it time if you have
a slow conection. Not the tha help text follows the mouse in real space.
Image from wiki commons
</div>
<canvas class="canC" id="canV"></canvas>
-->
<script src="src/index.js"></script>
</body>
</html>
JavaScript
// some text objects
var texts = [];
var mrx;
var mry;
var diffx = 0;
var diffy=0;
document.addEventListener('DOMContentLoaded', function() {
var button = document.createElement('button');
button.type = 'button';
button.innerHTML = '';
button.onclick = function() {
aText();
};
document.body.appendChild(button);
}, false);
function aText() {
var ntext = prompt("Type...");
texts.push({
text: ntext,
x: 100,
y: 100,
rrx: 100,
rry: 100
});
}
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.canvas.width = 700;
ctx.canvas.height = 400;
// variables used to get mouse position on the canvas
var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrollX = $canvas.scrollLeft();
var scrollY = $canvas.scrollTop();
// variables to save last mouse position
// used to see how far the user dragged the mouse
// and then move the text by that distance
var startX;
var startY;
var mdx;
var mdy;
// some test texts
texts.push({
text: "",
x: 20,
y: 100,
rrx: 20,
rry: 20
});
// some test texts
texts.push({
text: "",
x: 20,
y: 20,
rrx: 20,
rry: 20
});
texts.push({
text: "World",
x: 20,
y: 70,
rrx: 20,
rry: 70
});
// calculate width of each text for hit-testing purposes
ctx.font = "16px verdana";
for (var i = 0; i < texts.length; i++) {
var text = texts[i];
text.width = ctx.measureText(text.text).width+20;
text.height = 16+15;
}
// this var will hold the index of the selected text
var selectedText = -1;
// START: draw all texts to the canvas
draw();
// clear the canvas draw all texts
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < texts.length; i++) {
var text = texts[i];
ctx.fillText(text.text, text.x, text.y);
}
}
// test if x,y is inside the...