好的,所以我是 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/