JavaScript canvas實現(xiàn)刮刮樂案例
更新時間:2021年10月29日 16:45:34 作者:Q青N年
這篇文章主要為大家詳細介紹了JavaScript canvas實現(xiàn)刮刮樂案例,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了JavaScript canvas實現(xiàn)刮刮樂效果的具體代碼,供大家參考,具體內(nèi)容如下
效果圖

HTML代碼:
<div class="ggk">
<span id="span">200元</span>
<canvas id="canvas"></canvas>
</div>
css代碼:
.ggk {
width: 200px;
height: 100px;
border: 1px solid #000;
margin: 20px 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;
}
js代碼:
var canvas = document.getElementById("canvas")
init()
function init() {
canvas.width = 200;
canvas.height = 100;
var ctx = canvas.getContext("2d")
// 覆蓋一層灰色
ctx.save();
ctx.fillStyle = 'rgb(100,100,100)'
ctx.fillRect(0, 0, 200, 100)
draw(ctx)
pro()
}
// 隨機內(nèi)容
function pro() {
var span = document.getElementById("span")
var arr = ["100元", '謝謝惠顧', '200元', '謝謝惠顧', '謝謝惠顧', '謝謝惠顧', '500萬', '謝謝惠顧']
var num = Math.floor(Math.random() * (arr.length - 1))
var text = arr[num]
span.innerHTML = text
}
function draw(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.clearRect(x,y,20,20)
ctx.stroke()
}
}
// 鼠標(biāo)彈起事件
canvas.onmouseup = function(){
canvas.onmousemove = null
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
echarts實現(xiàn)橫向和縱向滾動條(使用dataZoom)
這篇文章主要給大家介紹了關(guān)于echarts使用dataZoom實現(xiàn)橫向和縱向滾動條的相關(guān)資料,最近項目中使用到echarts圖表,當(dāng)數(shù)據(jù)過多時需要添加橫向滾動條,需要的朋友可以參考下2023-08-08

