效果(完整代碼在底部):

實作(原理是比較簡單的):
1.定義標簽:
<canvas id="canvas"></canvas>
2.canvas基本css樣式:
canvas{
background-image: url(img/對比圖/1.1.png);
background-size: cover;
}
background-image: url(img/對比圖/1.1.png); 給個真人鋼鐵俠背景圖,
background-size: cover; 背景影像完全覆寫背景區域,
3. 開始js部分,獲取畫布,設定基本大小:
var canvas = document.querySelector("#canvas");
var ctx = canvas.getContext("2d");
canvas.width = 243;
canvas.height = 528;
4.繪制一張漫畫圖片覆寫在真人鋼鐵俠上面:
var img = new Image();
img.src = "img/對比圖/1.png";
img.onload=function(){
ctx.drawImage(img,0,0,243,528);
}
5.定義變數 isDown,判斷滑鼠是否是一直按壓著:
var isDown = false;
canvas.addEventListener('mousedown',function(){
isDown = true;
})
canvas.addEventListener('mouseup',function(){
isDown = false;
})
6.實作效果:
canvas.addEventListener('mousemove',function(event){
if(isDown){
//獲取滑鼠位置
let x = event.offsetX;
let y = event.offsetY;
//開始繪制路徑,繪制小圓球
ctx.beginPath();
ctx.fillStyle = "white";
ctx.arc(x,y,20,Math.PI*2,false);
ctx.fill();
ctx.closePath();
/*在源影像外顯示目標影像,只有源影像外的目標
影像部分會被顯示,源影像是透明的,*/
ctx.globalCompositeOperation = 'destination-out';
}
})
完整代碼:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
canvas{
background-image: url(img/對比圖/1.1.png);
background-size: cover;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.querySelector("#canvas");
var ctx = canvas.getContext("2d");
canvas.width = 243;
canvas.height = 528;
var img = new Image();
img.src = "img/對比圖/1.png";
img.onload=function(){
ctx.drawImage(img,0,0,243,528);
}
canvas.addEventListener('mousemove',function(event){
if(isDown){
let x = event.offsetX;
let y = event.offsetY;
ctx.beginPath();
ctx.fillStyle = "white";
ctx.arc(x,y,20,Math.PI*2,false);
ctx.fill();
ctx.closePath();
ctx.globalCompositeOperation = 'destination-out';
}
})
var isDown = false;
canvas.addEventListener('mousedown',function(){
isDown = true;
})
canvas.addEventListener('mouseup',function(){
isDown = false;
})
</script>
</body>
</html>
總結:
圖片:


下次再更個css特效,假期一直在玩Q_Q
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/274134.html
標籤:其他
上一篇:八皇后問題詳解
下一篇:編譯原理各章節知識點
