使用画布制作矩形覆盖图像。

4
我希望使用HTML5画布实现以下目标: goal 我的代码: 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();

为什么我画的矩形不会覆盖之前的图像? 有时候重新加载网站时,画布绘制的方式也很奇怪。
2个回答

2
在异步回调onload中绘制图像,结果会根据图像是否先加载或先调用canvas绘制而改变。尝试将绘制代码移入同一回调函数中。为了更有效地裁剪,可以使用非零环绕顺序规则:http://blogs.adobe.com/webplatform/2013/01/30/winding-rules-in-canvas/。简而言之:连续的canvas绘制调用,会根据点的顺序是顺时针还是逆时针来添加或减去前面调用的内容。请查看: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。
编辑:这消除了需要重复绘制的需要。效率,赢家。

1
你需要改变绘制对象的顺序。
// Why does this rectangle not overlay the previous image?
context.fillStyle = sectorColor;
context.fillRect(0, 0, canvasWidth, canvasHeight);

drawDday('clip');      
drawDday(); 

@DamianFrizzi 我想我复制了原始行而不是更改后的行。这是您的fiddle,带有更改:http://jsfiddle.net/3zHQv/ - Carth
很不幸,这没有任何区别。你使用哪个浏览器?有时加载JSFiddle时图像会被剪裁,有时则不会。此外,“背景中的透明图像”从未可见(甚至没有绘制)。 - damian
@DamianFrizzi 我试过Chrome和FF。我会再看一下,看它是否在交替出现。 - Carth
@DamianFrizzi,我没有看到我链接的新小提琴交替显示,但user3094783的答案更像是你想要的。 - Carth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接