why does the canvas drawn on second click?

  canvas, html, javascript, transform

I am flipping canvas using image click. When I clicked on image nothing event listener called but canvas did not flipped but when I clicked twice canvas flipped.

canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');

imgClicked?.addEventListener("click", function () {
    img = new Image();
    img.src = canvas.toDataURL();
    
    var flipH = document.getElementById('leftRightIp').checked,
        flipV = document.getElementById('topDownIp').checked;
    
    flipImage(img, ctx, flipH, flipV);
});


function flipImage(image, ctx, flipH, flipV) {
    var width = canvas.width;
    var height = canvas.height;

    var scaleH = flipH ? -1 : 1, // Set horizontal scale to -1 if flip horizontal
        scaleV = flipV ? -1 : 1, // Set verical scale to -1 if flip vertical
        posX = flipH ? width * -1 : 0, // Set x position to -100% if flip horizontal 
        posY = flipV ? height * -1 : 0; // Set y position to -100% if flip vertical

    ctx.save(); // Save the current state
    ctx.scale(scaleH, scaleV); // Set scale to flip the image
    ctx.drawImage(image, posX, posY, width, height); // draw the image
    ctx.restore(); // Restore the last saved state
};

I don’t know why but canvas is flipping when image clicked twice. where am I doing it wrong?

Source: Ask Javascript Questions

LEAVE A COMMENT