Search code examples
javascripthtmlcanvasgetboundingclientrect

JavaScript canvas - clearImage() - canvas.getBoundingClientRect


I cannot clear the cursor image (canvas.getBoundingClientRect) after the cursor moves across the canvas element! I am left with a trail of appended images on the canvas.

  • How can I clear the trail of appended images and still keep my customized cursor (canvas.getBoundingClientRect) visible each time the canvas is cleared?

See my code :

<script>
window.addEventListener("load", CanvasProperties, false);

//Global Variables
var canvas, context;     

// Canvase Element - 2D Properties
function CanvasProperties(){
   canvas = document.getElementById("canvas");        
   context = canvas.getContext("2d");        
   window.addEventListener("mousemove", CustomCursor, false);};

// Customized Cursor for Game's Canvas    
   function CustomCursor(e){
   var canvasRect = canvas.getBoundingClientRect(); 
   var xPosition = e.clientX - 5 - canvasRect.left;
   var yPosition = e.clientY - 5 - canvasRect.top;
   var img = new Image();
   img.src = "hero.png";
   context.drawImage(img, xPosition, yPosition, 80, 80);};

</script>

Solution

  • Yeah, this one was really hard to google. The answer I like the best: https://stackoverflow.com/a/2142549/607407

    function CustomCursor(e){
       var canvasRect = canvas.getBoundingClientRect(); 
    
       var img = new Image();
       img.src = "https://crossorigin.me/https://www.gravatar.com/avatar/5a061a72feb5b6580dadd5dcbc92d3b5?s=64&d=identicon&r=PG";
       var xPosition = e.clientX - 5 - canvasRect.left-img.naturalWidth/2;
       var yPosition = e.clientY - 5 - canvasRect.top- img.naturalHeight/2;
    
       context.clearRect(0, 0, canvas.width, canvas.height);
       context.drawImage(img, xPosition, yPosition, 80, 80);
    };
    

    Snippet:

    //Global Variables - which is wrong
    var canvas, context;     
    
    // Canvase Element - 2D Properties
    function CanvasProperties(){
       canvas = document.getElementById("canvas");   
       canvas.width = window.innerWidth;
       canvas.height = window.innerHeight;
       context = canvas.getContext("2d");        
       window.addEventListener("mousemove", CustomCursor, false);
    }
    // Customized Cursor for Game's Canvas    
    function CustomCursor(e){
       var canvasRect = canvas.getBoundingClientRect(); 
    
       var img = new Image();
       img.src = "https://crossorigin.me/https://www.gravatar.com/avatar/5a061a72feb5b6580dadd5dcbc92d3b5?s=64&d=identicon&r=PG";
       var xPosition = e.clientX - 5 - canvasRect.left-img.naturalWidth/2;
       var yPosition = e.clientY - 5 - canvasRect.top- img.naturalHeight/2;
       
       context.clearRect(0, 0, canvas.width, canvas.height);
       context.drawImage(img, xPosition, yPosition, 80, 80);
    };
    
    CanvasProperties();
    <canvas width="300" height="300" id="canvas" />