Javascript html5画布中心圆
好吧,我是画布新手,我正在努力学习。我已经创造了一些低于这类作品的东西- 你看到中间有一个圆圈,我希望它是透明的,所以,很明显,如果你看下面的代码,有两个路径或对象,无论它们叫什么,它们都是相互重叠的。显然不是我需要的 我的问题是:如何让画布元素/对象占据屏幕大小,并以透明的中间显示背景?我们的目标是制作这样的东西。我最终会从一个圆圈变成一个字母,但现在我不知道如何制作一个中心透明的“面具”Javascript html5画布中心圆,javascript,html,canvas,Javascript,Html,Canvas,好吧,我是画布新手,我正在努力学习。我已经创造了一些低于这类作品的东西- 你看到中间有一个圆圈,我希望它是透明的,所以,很明显,如果你看下面的代码,有两个路径或对象,无论它们叫什么,它们都是相互重叠的。显然不是我需要的 我的问题是:如何让画布元素/对象占据屏幕大小,并以透明的中间显示背景?我们的目标是制作这样的东西。我最终会从一个圆圈变成一个字母,但现在我不知道如何制作一个中心透明的“面具” var canvas = document.getElementById('c'); // resiz
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';
画布是透明的,是的,但我说的是一个倒置的透明度。在实际的画布元素(如矩形)有一个颜色和中间的某个地方,有一个透明的形状。就像下面的答案所显示的一样。很好,我稍后会充分分析为什么这个方法有效,但它确实有效。谢谢我稍后会问我怎样才能把那个圆圈变成一封信。我知道画布有文本属性,我会看看我是否可以使用它们。在设置合成模式后,你可以在上面绘制任何东西。只需使用
fillText(txt,x,y)
来绘制文本即可。好吧,如果你想构建很棒的东西,有很多东西需要学习,有很多可能性,还有一个很好的工具。谢谢