javascript - html5 Canvas 中心圆

标签 javascript html canvas

好的,所以我是 canvas 的新手,我正在努力学习。我在下面创建了一些可以正常工作的东西 - JSFiddle demo .

你看到中间有一个圆圈,我希望它是透明的,所以,很明显,如果你看下面的代码,就会有两个路径或对象,无论它们叫​​什么,它们相互重叠.显然,这不是我需要的。

我的问题是:我如何让 Canvas 元素/对象接管屏幕大小,中间透明显示背景?目标是做出这样的东西 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);

    }
}

最佳答案

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

// 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

关于javascript - html5 Canvas 中心圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21974433/

相关文章:

javascript - 将中国 MS Azure 认知服务与全局 WEB 认知服务整合

javascript - Chrome 中的 HTML5 视频,安全错误 : DOM Exception 18

javascript - 如何使用 HTML5 Canvas 水平翻转 Sprite ?

javascript - jquery 可嵌套不更新

javascript - 如何在javascript中处理 '&'、 '('、 ')'

html - IE、Chrome 和 FireFox 的保存密码行为说明

html - 文字和图片在同一行

php - 使用 PHP 从 Canvas 保存没有黑色背景的图像

Javascript slice 没有给我正确的数组长度值

javascript - 如何在博客文章标题后面插入图片