I have an HTML5 canvas with the size of 392x392 in which I draw something. I am trying to resize the content of that canvas into another canvas with the size of 28x28 pixels.
The following approach works fine, except that I have to click the "resize image" button twice - why is that and how can I fix it?
function resize() {
//get the base64 string of the Image
var dataURL = canvas.toDataURL();
//draw the base64 string into a 28x28 canvas (for resizing)
var img = new Image();
img.src = dataURL;
resizedCtx.drawImage(img, 0, 0, 28, 28);
}
<canvas id="canvas" width="392" height="392" style="border:1px solid;"></canvas>
<br>
<br>
<input type="button" value="resize image" id="btn" size="30" onclick="resize()">
<br>
<br>
<canvas id="resizedCanvas" width="28" height="28" style="border:1px solid;"></canvas>
<script>
canvas = document.getElementById('canvas');
ctx = canvas.getContext("2d");
resizedCanvas = document.getElementById('resizedCanvas');
resizedCtx = resizedCanvas.getContext('2d');
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 280, 280);
</script>
Thanks in advance!