效果图:
核心就是使用ctx.globalCompositeOperation = 'destination-out';
全部代码:
.ggk{
width:200px;
height: 100px;
border:1px solid #ccc;
margin:0 auto;
color:red;
position: relative;
}
.ggk span{
position: absolute;
width:100%;
height: 100%;
text-align: center;
font-size:50px;
line-height: 100px;
}
canvas{
position: absolute;
left:0;
top:0;
}
200元
var canvas = document.getElementById("canvas");
init();
function init(){
canvas.width = 200;
canvas.height = 100;
var ctx = canvas.getContext("2d");
productResult();
drawCover(ctx);
drawStroke(ctx);
}
//往span内填充内容
function productResult(){
var span = document.getElementById("span");
var arr = ['100元','100元','200元','300元','谢谢','谢谢','谢谢','谢谢','谢谢','谢谢'];
var text = arr[randomInt(0,arr.length-1)];
span.innerHTML = text;
}
//产生随机值
function randomInt(from,to){
return parseInt( Math.random()*(to-from+1)+from );
}
//绘制覆盖层==》灰色
function drawCover(ctx){
ctx.save();
ctx.fillStyle = "rgb(100,100,100)";
ctx.fillRect(0,0,200,100);
ctx.restore();
}
function drawStroke(ctx){
canvas.onmousedown = function(e){
var downX = e.offsetX;
var downY = e.offsetY;
ctx.beginPath();
ctx.globalCompositeOperation = 'destination-out';
ctx.lineWidth = 10;
ctx.moveTo(downX,downY);
canvas.onmousemove = function(e){
var x = e.offsetX;
var y = e.offsetY;
ctx.lineTo(x,y);
ctx.stroke();
}
}
canvas.onmouseup = function(){
canvas.onmousemove = null;
}
}
每日分享效果附带视频:https://www.3mooc.com/front/couinfo/998