Nik Nik - 27 days ago 5
Javascript Question

Javascript Why when i use drawImage in `mousemove` i get bad image?

I would like to draw a image when action mousemove, but when i use drawImage in

mousemove
i get bad image (see right image):

enter image description here

Why the image is drawn badly when action
mousemove
?

P.S.: i would like draw right image with quality left image;



var canvas = document.getElementById('canvas_test');
var context = canvas.getContext("2d");
var img_test__src = 'http://image.prntscr.com/image/8233c5a42e7e4b40a19c64d8e9b892ee.png';

var img = new Image();
img.src = img_test__src;
img.onload = function() {
context.save();
context.beginPath();
context.drawImage(img, 100, 100, 71, 71);
context.closePath();
context.restore();
};

canvas.addEventListener('mousemove', function(evt) {
var img = new Image();
img.src = img_test__src;
img.onload = function() {
context.save();
context.beginPath();
context.drawImage(img, 200, 100, 71, 71);
context.closePath();
context.restore();
};
});

#canvas_test {
background: #000;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas_test" width="500" height="500"></canvas>




Answer

You draw the image multiple times at once. So it overlaps and you see that effect. Change mousemove to mouseenter and it will work, when you first enter. If you enter again you even more see an artifact because of alpha overlap on multiple draws.

Clear the canvas area before draw to ommit this, if you have to use mousemove or other events that fire more than once.

https://jsfiddle.net/uy55o8v5/