html5画布中心圈

时间:2014-02-23 20:59:14

标签: javascript html5 canvas

好的,所以我是画布的新手,我正在努力学习。我在下面创建了一些东西 - JSFiddle demo

你看到中间有一个圆圈,我希望它是透明的,所以,显然,如果你看下面的代码,有两个路径或对象,无论它们被称为什么,它们相互叠加。显然不是我需要的。

我的问题是:如何让画布元素/对象接管屏幕大小,透明的中间显示背景?目标是制作类似http://www.jcsuzanne.com/的内容。我最终会从一个圆圈到另一个圆圈,但是现在我不知道如何制作一个透明中心的“面具”。

var canvas = document.getElementById('c');

// resize the canvas to fill browser window dynamically
window.addEventListener('resize', resizeCanvas, false);

function resizeCanvas() {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        /**
         * Your drawings need to be inside this function otherwise they will be reset when 
         * you resize the browser window and the canvas goes will be cleared.
         */
        drawStuff(); 
}
resizeCanvas();

function drawStuff() {

    if (canvas.getContext){

        var context = canvas.getContext('2d');
        var centerX = canvas.width / 2;
        var centerY = canvas.height / 2;
        var radius = 70;

        context.beginPath();
        context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
        context.fillStyle = 'rgba(0,0,0,0)';
        context.fill();
        context.lineWidth = 5;
        context.stroke();

        context.beginPath();
        context.fillStyle = 'rgba(0,0,0,0.5)';
        context.fill();
        context.fillRect(0,0,window.innerWidth,window.innerHeight);

    }
}

1 个答案:

答案 0 :(得分:1)

您可以稍微重新组织线条并使用复合模式在叠加层中“打孔”整个线条:

// fill background first
context.fillStyle = 'rgba(0,0,0,0.5)';
context.fillRect(0,0,window.innerWidth,window.innerHeight);

// define the arc path
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);

// stroke it
context.lineWidth = 5;
context.stroke();

// make alpha solid (the color doesn't matter)
context.fillStyle = 'rgba(0,0,0,1)';

// change composite mode and fill
context.globalCompositeOperation = 'destination-out';
context.fill();

// reset composite mode to default
context.globalCompositeOperation = 'source-over';

Modified fiddle