As I understand it is necessary to wait for the picture to load. And only after that draw it. That is, it is necessary to take this drawing out of the first cycle.
Also drawing on the center of the picture is completely exposed to the general principles:
ΠΊΠΎΡΠ΄ΠΈΠ½Π°ΡΠ°ΠΠ½ΡΡΡΠ΅Π½Π½Π΅ΠΉΠΠ°ΡΡΠΈΠ½ΠΊΠΈΠΠΎX = Π¨ΠΈΡΠΈΠ½Π°ΠΠ±Π΅ΡΡΠΊΠΈΠΠΎX / 2 - ΡΠΈΡΠΈΠ½Π°ΠΠ°ΡΡΠΈΠ½ΠΊΠΈ / 2;
because coordinates start from the left upper corner, then in the Π¨ΠΈΡΠΈΠ½Π°ΠΠ±Π΅ΡΡΠΊΠΈΠΠΎX / 2 coordinate by Π¨ΠΈΡΠΈΠ½Π°ΠΠ±Π΅ΡΡΠΊΠΈΠΠΎX / 2 will be a left border of the picture. And so that it was in the center - it is necessary to shift it to the left. How much? Correct - also half.
knowing this, it turns out:
ctx.drawImage(coin, 70 * (i + .5) - (coin.width / 2), 5);
Total:
function getRandomInt() { return Math.floor(Math.random() * (255 - 0)) + 0; } $(document).ready(function() { var coin = new Image(); var rectCount = 10; coin.src = 'http://i.stack.imgur.com/Mnyl3.png'; var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); for (var i = 0; i < rectCount; i++) { var coordinates = 70 * i; ctx.fillStyle = "rgb(" + getRandomInt() + ", " + getRandomInt() + ", " + getRandomInt() + ")"; ctx.fillRect(coordinates, 0, 70, 70); ctx.font = "bold 30px Verdana,sans-serif"; ctx.lineWidth = 1; ctx.textAlign = 'center'; ctx.strokeText("Π", 70 * (i + .5), 50); } coin.onload = function() { for (var i = 0; i < rectCount; i++) { ctx.drawImage(coin, 70 * (i + .5) - (coin.width / 2), 5); } }; });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <canvas id="canvas" width="700" height="70"> <!-- Insert fallback content here --> </canvas>