Make a rectangular overlay image with a canvas

I want to do the following with an HTML5 canvas:

goal

My code: jsfiddle

// Options
var maxImageWidth = 250,
    maxImageHeight = 196,
    radius = 50;

var canvas = $('#ddayCanvas'),
    canvasWidth = canvas.width(),
    canvasHeight = canvas.height(),
    sectorColor = $('.product-box').css('background-color'),
    context = canvas[0].getContext('2d'),
    imageSrc = canvas.data('image');  


function drawDday (option) {

    var imageObj = new Image();
    imageObj.onload = function() {

        if (option == 'clip'){
            context.save();
            context.clip();
        }

        var imageWidth = imageObj.width,
            imageHeight = imageObj.height;

        if (imageWidth > maxImageWidth){
            imageHeight = imageHeight - (imageWidth - maxImageWidth);
            imageWidth = maxImageWidth;
        }

        if (imageHeight > maxImageHeight) {
            imageWidth = imageWidth - (imageHeight - maxImageHeight);
            imageHeight = maxImageHeight;
        }

        context.drawImage(imageObj, Math.ceil((canvasWidth - imageWidth) / 2), Math.ceil((canvasHeight - imageHeight) / 2), imageWidth, imageHeight);

    };

    imageObj.src = imageSrc;  

}

drawDday(); 

// Why does this rectangle not overlay the previous image?
context.fillStyle = sectorColor;
context.fillRect(0, 0, canvasWidth, canvasHeight);

drawDday('clip');      

context.restore();
context.moveTo(0, 0);
context.beginPath();
context.fillStyle = '#fff';
context.arc(canvasWidth / 2, canvasHeight/2, radius, 0, 2*Math.PI);
context.fill();

Why doesn't the rectangle I draw overlap the previous image? It is also strange that the canvas is drawn in different ways, sometimes when the site is reloaded.

+4
source share
2 answers

You have an image that is drawn in the onload asynchronous callback. The result will vary depending on whether the image is loaded first or drawing drawing is called first.

Try moving the drawing code to the same callback.

: http://blogs.adobe.com/webplatform/2013/01/30/winding-rules-in-canvas/

TL;DR: , .

: http://jsfiddle.net/jJjt7/2/

context.fillStyle = sectorColor;
context.rect(0, 0, canvasWidth, canvasHeight);
context.arc(canvasWidth/2, canvasHeight/2, radius, 0, Math.PI*2, true);
context.fill();

, () . " ". true.

: . , FTW.

+2

, .

// Why does this rectangle not overlay the previous image?
context.fillStyle = sectorColor;
context.fillRect(0, 0, canvasWidth, canvasHeight);

drawDday('clip');      
drawDday(); 
+1

All Articles