Skip to content Skip to sidebar Skip to footer

Canvas Image Not Display When Load

Here i am trying to make circle using multiple arc shape. like following: Problem: Now, issue is when page load i call function which draw circle using arc and draw image in to th

Solution 1:

The point here is that you should have to wait until the image is loaded before actually draw it.

My best option, in order to get your code working, is to wrap all the canvas drawing into an image.onload function, because in this way you can be sure it will be rendered once you start actually drawing on it.

I post you the code on a working Plunkr

var startAngle = 0;
var arc = Math.PI / 6;
var ctx;

var leftValue = 275;
var topValue = 300;

var wheelImg = "http://i.stack.imgur.com/wwXlF.png";

functiondrawWheelImg() {
    var canvas = document.getElementById("canvas");
    if (canvas.getContext) {
        var imgName = wheelImg;
        var img = newImage();
        img.src = wheelImg;

        img.onload = function() {
            var outsideRadius = 260;
            var textRadius = 217;
            var insideRadius = 202;

            ctx = canvas.getContext("2d");

            for (var i = 0; i < 12; i++) {
                var angle = startAngle + i * arc;

                ctx.beginPath();
                ctx.arc(leftValue, topValue, outsideRadius, angle, angle + arc, false);
                ctx.arc(leftValue, topValue, insideRadius, angle + arc, angle, true);
                ctx.fill();
                ctx.closePath();
                ctx.beginPath();
                ctx.arc(leftValue, topValue, outsideRadius, angle, angle + arc, false);
                ctx.shadowBlur = 3;
                ctx.shadowColor = "#A47C15";
                ctx.stroke();
                ctx.closePath();

                ctx.save();
                ctx.translate(leftValue + Math.cos(angle + arc / 2) * textRadius,
                    topValue + Math.sin(angle + arc / 2) * textRadius);
                ctx.rotate(angle + arc / 2 + Math.PI / 2);
                ctx.drawImage(img, -44, -25, 50, 40);
                ctx.restore();
            }
        }
    }
}

drawWheelImg();
<!DOCTYPE html><html><head><linkhref="style.css"></head><body><canvasid="canvas"width="550"height="400"></canvas><scriptsrc="script.js"></script></body></html>

Post a Comment for "Canvas Image Not Display When Load"