JS.Canvas:镂空文字

参考:

https://blog.csdn.net/weixin_29209805/article/details/112116441
https://developer.mozilla.org/en-US/docs/Web/API/CSS_Font_Loading_API
https://developer.mozilla.org/en-US/docs/Web/API/Document/fonts
JS实现canvas图层
globalCompositeOperation
globalAlpha
https://www.runoob.com/tags/html-colorname.html

 

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>镂空文字</title>
<style>
canvas { border:1px solid gray; margin:0 auto; display:block; }
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const font = new FontFace("FZCCHJT", "url(方正超粗黑简体.ttf)");
document.fonts.add(font);
font.load();

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var img1 = new Image();
img1.src = 'sea.webp';
img1.onload = function() {
document.fonts.ready.then(function () {
	canvas.width = img1.width;
	canvas.height = img1.height;
	
	//background
	var canvas1 = document.createElement('canvas');
	canvas1.width = img1.width;
	canvas1.height = img1.height;
	var ctx1 = canvas1.getContext('2d');	
	ctx1.drawImage(img1,0,0);
 	//ctx1.globalCompositeOperation = "lighter";
 	ctx1.globalAlpha = 0.8;
	ctx1.fillStyle = 'black';
	ctx1.fillRect(0, 0, canvas1.width, canvas1.height);	
	
	var canvas2 = document.createElement('canvas');
	canvas2.width = img1.width;
	canvas2.height = img1.height;
	var ctx2 = canvas2.getContext('2d');
	ctx2.drawImage(img1,0,0);
	ctx2.globalCompositeOperation = "destination-in";
	ctx2.font = '400px FZCCHJT';
  	ctx2.fillText('海', 0, 350);
	
	var canvas3 = document.createElement('canvas');
	canvas3.width = img1.width;
	canvas3.height = img1.height;
	var ctx3 = canvas3.getContext('2d');
	ctx3.drawImage(img1,0,0);
	ctx3.globalCompositeOperation = "destination-in";
	ctx3.font = '400px FZCCHJT';
	ctx3.fillText('浪', canvas3.width/2 + 100, 500);

	ctx.drawImage(canvas1, 0, 0);	
	ctx.drawImage(canvas2, 0, 0);
	ctx.drawImage(canvas3, 0, 0);
});
}
</script>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值