Skip to content

Instantly share code, notes, and snippets.

@plugn
Created July 10, 2024 16:55
Show Gist options
  • Save plugn/dbb73af4d10613600619b5d30a2760d0 to your computer and use it in GitHub Desktop.
Save plugn/dbb73af4d10613600619b5d30a2760d0 to your computer and use it in GitHub Desktop.
Paste image from clipboard.
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<p>Hit Cmd or Ctrl V with an image on your clipboard. Click on image and hit Backspace to remove.</p>
// window.addEventListener('paste', ... or
document.onpaste = function(event){
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
console.log(JSON.stringify(items)); // will give you the mime types
var blob = items[0].getAsFile();
var reader = new FileReader();
reader.onload = function(event){
// console.log(event.target.result); // data url!
loadImage(event.target.result);
}
reader.readAsDataURL(blob);
}
function loadImage(dataURL) {
// load image from data url
var img = new Image();
img.onload = function() {
// canvas.setAttribute('width', img.width);
// canvas.setAttribute('height', img.height);
document.body.appendChild(img);
$(img).draggable();
};
img.src = dataURL;
}
var lastClickedImage = null;
function unselectLastClicked() {
if (lastClickedImage) {
lastClickedImage.style.boxShadow = "";
}
lastClickedImage = null;
}
function selectImage(img) {
img.style.boxShadow = '2px 2px 15px 2px black';
lastClickedImage = img;
}
document.addEventListener('click', function(e) {
if (/img/i.test(e.target.tagName)) {
selectImage(e.target);
} else {
unselectLastClicked();
}
});
document.addEventListener('keydown', function(e) {
if (e.keyCode === 8) {
e.preventDefault();
lastClickedImage.remove();
unselectLastClicked();
} else {
unselectLastClicked();
}
});
body {
font-family:Monospace;
}
p {
margin:0;
padding:0;
position:absolute;
top:10px;
left:10px;
z-index:-10;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment