JSFiddle - React, Tailwind, and code Playground
HTML
<div id="canvas">An interactive application using a canvas<br/></div>
<input id="hidden-input" class="hidden" type="text" value=""/>
CSS
.hidden {
position: absolute;
bottom: 0;
left: 0;
width: 10px;
height: 10px;
display: block;
font-size: 1;
z-index: -1;
color: transparent;
background: transparent;
overflow: hidden;
border: none;
padding: 0;
resize: none;
outline: none;
-webkit-user-select: text;
user-select: text; /* Because for user-select:none, Safari won't allow input */
}
JavaScript
var hiddenInput = $("#hidden-input");
var focusHiddenArea = function() {
// In order to ensure that the browser will fire clipboard events, we always need to have something selected
hiddenInput.val(' ');
hiddenInput.focus().select();
};
// Set clipboard event listeners on the document.
['cut', 'copy', 'paste'].forEach(function(event) {
document.addEventListener(event, function(e) {
console.log(event);
focusHiddenArea();
e.preventDefault();
});
});
// Keep the hidden text area selected
$(document).mouseup(focusHiddenArea);
// This is an interactive web application using a canvas to render. We use the
// hidden input area to make sure that cut, copy, and paste events are always fired.
(function() {
// Creates a new canvas element and appends it as a child
// to the parent element, and returns the reference to
// the newly created canvas element
function createCanvas(parent, width, height) {
canvas.node = document.createElement('canvas');
canvas.context = canvas.node.getContext('2d');
canvas.node.width = width || 300;
canvas.node.height = height || 300;
parent.appendChild(canvas.node);
return canvas;
}
function init(container, width, height, fillColor) {
var canvas = createCanvas(container, width, height);
var ctx = canvas.context;
// define a custom fillCircle method
ctx.fillCircle = function(x, y, radius, fillColor) {
this.fillStyle = fillColor;
this.beginPath();
this.moveTo(x, y);
this.arc(x, y, radius, 0, Math.PI * 2, false);
this.fill();
};
ctx.clearTo = function(fillColor) {
ctx.fillStyle = fillColor;
ctx.fillRect(0, 0, width, height);
};
ctx.clearTo(fillColor || "#ddd");
// bind mouse events
canvas.node.onmousemove = function(e) {
if (!canvas.isDrawing) {
...