0

I am trying to make a cursor changer, where the user can upload an image, and it will be the cursor anywhere on the document <body>. However it doesn't seem to work. I have tried .append and .appendChild, but it doesn't seem to work. Where have I gone wrong?

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    
    reader.onload = function(e) {
      $('#uploaded1').attr('src', e.target.result);
        $("#upload-cursor").css("display", "block");
        $("#upload-cursor").click(function() {

              $("body").css("cursor", "url(" + e.target.result + "), auto");
          
        });
    };
    
    reader.readAsDataURL(input.files[0]);
  }
}

$("#imgInp").change(function() {
  readURL(this);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h5>Upload Cursor</h5>
<form runat="server">
  <input type='file' id="imgInp">
    <img id="uploaded1" src="#" width="50px" height="50px">
    <br>
</form>
<button id="upload-cursor" style="display: none;">Create Cursor</button>
topsoftwarepro
  • 773
  • 5
  • 19
  • 2
    Not all browsers support all image formats, and the maximum size the image can have, might be limited as well - https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Basic_User_Interface/Using_URL_values_for_the_cursor_property#Limitations – CBroe Jul 06 '20 at 09:03
  • 1
    Your code worked fine for me - I saved SO's favicon.ico, selected that that and it worked fine. – freedomn-m Jul 06 '20 at 09:17

1 Answers1

2

As the above answer, you image size might be big so do resize the Image.

to resize use the File API, then you can process the images with the canvas element.

This Mozilla Hacks blog post walks you through most of the process. For reference here's the assembled source code from the blog post:

// from an input element
var filesToUpload = input.files;
var file = filesToUpload[0];

var img = document.createElement("img");
var reader = new FileReader();  
reader.onload = function(e) {img.src = e.target.result}
reader.readAsDataURL(file);

var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);

var MAX_WIDTH = 800;
var MAX_HEIGHT = 600;
var width = img.width;
var height = img.height;

if (width > height) {
    if (width > MAX_WIDTH) {
        height *= MAX_WIDTH / width;
        width = MAX_WIDTH;
    }
} 
else {
    if (height > MAX_HEIGHT) {
        width *= MAX_HEIGHT / height;
        height = MAX_HEIGHT;
    }
}

canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);

var dataurl = canvas.toDataURL("image/png");

//Post dataurl to the server with AJAX

Resizing before uploading:

HTML5 Pre-resize images before uploading

Maestro
  • 865
  • 1
  • 7
  • 24
Prabesh Gouli
  • 413
  • 3
  • 11