简介
实现功能,通过url传参选择扑克牌,桌面同时打开两个以上该窗口,扑克牌可以在窗口之间移动。
在线演示
屏幕坐标和窗口通信
实现代码
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta content="always" name="referrer">
<meta name="theme-color" content="#ffffff">
<meta name="description" content="">
<title>屏幕坐标和窗口通信</title>
<style>
.card{
position: absolute;
width: 156px;
height: 194px;
background-image: url(./imgs/card.jpg);
background-repeat: no-repeat;
background-position: -1px -194px;
border-radius: 13px;
box-shadow: 8px 10px 10px 1px rgba(0,0,0,0.5);
}
</style>
</head>
<body>
<div>
<img draggable="false" class="card" />
</div>
<script>
//扑克(英文:Poker),代指两种含义:
//一是指纸牌(playing cards);
//二是指以用纸牌来玩的游戏,称为扑克游戏,如德州扑克。
//一副扑克牌有54张牌,其中52张是正牌,另2张是副牌(大王和小王)。
//52张正牌又均分为13张一组,并以黑桃、红桃、梅花、方块四种花色表示各组,
//每组花色的牌包括从1-10(1通常表示为A)以及J、Q、K标示的13张牌,玩法千变万化,多种玩法。
const card = document.querySelector('.card')
const channel = new BroadcastChannel('card')
//每种花色刚好13张,指每个季节有13个星期。
const cardenum = {
A: 0,
2: 1,
3: 2,
4: 3,
5: 4,
6: 5,
7: 6,
8: 7,
9: 8,
10: 9,
J: 10,
Q: 11,
K: 12
}
//扑克牌中的四种花色,即:黑桃(spade)、红桃(heart)、梅花(club)、方块(diamond)、代表一年中的春夏秋冬四季,
//黑桃、梅花代表夜晚,红桃、方块代表白天。
//除大王(red Joker)、小王( black Joker)外,扑克牌一共52张,指一年有52个星期。其中J、Q和K共12张,代表一年有12个月。
//而扑克牌里的——A指“至尊(Ace)”
//K指“国王(King)”
//Q指“王后(Queen)”
//J指的是“宫内的仆人杰克(Jack)”
const colorenum = {
clubs:0,//梅花
diamonds:1,//方块
spades:2,//黑桃
hearts:3,//红心
joker:4//副牌 大王 小王
}
channel.onmessage=(e)=>{
const clientPoints = screenToClient(...e.data)
card.style.left = clientPoints[0]+'px'
card.style.top = clientPoints[1]+'px'
}
card.onmousedown=(e)=>{
let x = e.pageX -card.offsetLeft;
let y = e.pageY -card.offsetTop;
window.onmousemove=(e)=>{
const cx=e.pageX-x
const cy=e.pageY-y
card.style.left=cx+'px'
card.style.top=cy+'px'
const screenPoints=clientToScreen(cx,cy)
channel.postMessage(screenPoints)
}
window.onmouseup=()=>{
window.onmousemove=null
window.onmouseup=null
}
}
function barHeight(){
return window.outerHeight - window.innerHeight
}
function clientToScreen(x,y){
const screenX = x+window.screenX
const screenY = y+window.screenY+barHeight()
return [screenX,screenY]
}
function screenToClient(x,y){
const clientX=x-window.screenX
const clientY=y-window.screenY-barHeight()
return [clientX,clientY]
}
function init(){
//?type=A
const url = new URL(location.href)
const type = url.searchParams.get('type')||'A'//A 2 3 4 5 6 7 8 9 10 J Q K
const color = url.searchParams.get('color')||'clubs'// clubs diamonds spades hearts
//console.log(cardenum[type], colorenum[color],-1+cardenum[type]*156,-194*colorenum[color])
card.style.backgroundPosition = `${-1-156*cardenum[type]}px ${-194*colorenum[color]}px`
//card.src = `./${type}.jpg`
}
init()
</script>
</body>
</html>