• canvas基础3 -- 交互


    点击交互

    使用 isPointInPath(x, y) 判断鼠标点击位置在不在图形内

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <title>Document</title>
    7. </head>
    8. <body>
    9. <canvas id="canvas" style="border:1px solid #ccc;display:block;margin:10px auto;"></canvas>
    10. </div>
    11. <script>
    12. const canvas = document.getElementById('canvas')
    13. canvas.width = 800
    14. canvas.height = 800
    15. const context = canvas.getContext('2d')
    16. const balls = []
    17. for(let i = 0; i < 10; i++) {
    18. const ball = {
    19. x: Math.random() * canvas.width,
    20. y: Math.random() * canvas.height,
    21. r: Math.random() * 50 + 20
    22. }
    23. balls[i] = ball
    24. }
    25. draw()
    26. canvas.addEventListener('mouseup', detect)
    27. function draw() {
    28. for(let i = 0; i < balls.length; i++) {
    29. context.beginPath()
    30. context.arc(balls[i].x, balls[i].y, balls[i].r, 0, Math.PI*2)
    31. context.fillStyle = '#058'
    32. context.fill()
    33. }
    34. }
    35. function detect(event) {
    36. const x = event.clientX - canvas.getBoundingClientRect().left
    37. const y = event.clientY - canvas.getBoundingClientRect().top
    38. for (let i = 0; i < balls.length; i++) {
    39. context.beginPath()
    40. context.arc(balls[i].x, balls[i].y, balls[i].r, 0, Math.PI * 2)
    41. if (context.isPointInPath(x, y)) {
    42. context.fillStyle = 'red'
    43. context.fill()
    44. }
    45. }
    46. }
    47. </script>
    48. </body>
    49. </html>

    图示:

    鼠标移动事件

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <title>Document</title>
    7. </head>
    8. <body>
    9. <canvas id="canvas" style="border:1px solid #ccc;display:block;margin:10px auto;"></canvas>
    10. </div>
    11. <script>
    12. const canvas = document.getElementById('canvas')
    13. canvas.width = 800
    14. canvas.height = 800
    15. const context = canvas.getContext('2d')
    16. const balls = []
    17. for(let i = 0; i < 10; i++) {
    18. const ball = {
    19. x: Math.random() * canvas.width,
    20. y: Math.random() * canvas.height,
    21. r: Math.random() * 50 + 20
    22. }
    23. balls[i] = ball
    24. }
    25. draw()
    26. canvas.addEventListener('mousemove', detect)
    27. function draw(x, y) {
    28. context.clearRect(0, 0, canvas.width, canvas.height)
    29. for(let i = 0; i < balls.length; i++) {
    30. context.beginPath()
    31. context.arc(balls[i].x, balls[i].y, balls[i].r, 0, Math.PI*2)
    32. if(context.isPointInPath(x, y)) {
    33. context.fillStyle = 'red'
    34. } else {
    35. context.fillStyle = '#058'
    36. }
    37. context.fill()
    38. }
    39. }
    40. function detect(event) {
    41. const x = event.clientX - canvas.getBoundingClientRect().left
    42. const y = event.clientY - canvas.getBoundingClientRect().top
    43. draw(x, y)
    44. }
    45. </script>
    46. </body>
    47. </html>

    图示:

    在Canvas上使用HTML元素进行交互

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <title>Document</title>
    7. <style>
    8. #canvas-wrapper {
    9. width: 1200px;
    10. height: 800px;
    11. position: relative;
    12. margin: 20px auto;
    13. }
    14. #canvas {
    15. border: 1px solid #aaa;
    16. }
    17. #controller {
    18. position: absolute;
    19. top: 30px;
    20. left: 30px;
    21. background-color: rgba(0, 85, 116, 0.7);
    22. padding: 5px 20px 25px 20px;
    23. border-radius: 10px 10px;
    24. }
    25. #controller h1 {
    26. color: white;
    27. font-weight: bold;
    28. font-family: Microsoft Yahei;
    29. }
    30. #controller #canvas-btn {
    31. display: inline-block;
    32. background-color: #8b0;
    33. color: white;
    34. font-size: 14px;
    35. padding: 5px 15px;
    36. border-radius: 6px;
    37. text-decoration: none;
    38. margin-top: 10px;
    39. margin-right: 20px;
    40. }
    41. #controller #canvas-btn:hover {
    42. background-color: #7a0;
    43. }
    44. #controller .color-btn {
    45. display: inline-block;
    46. font-size: 14px;
    47. padding: 5px 15px;
    48. border-radius: 6px;
    49. text-decoration: none;
    50. margin-top: 10px;
    51. margin-right: 5px;
    52. }
    53. #white-color-btn {
    54. background: white;
    55. }
    56. #black-color-btn {
    57. background: black;
    58. }
    59. </style>
    60. </head>
    61. <body>
    62. <div id="canvas-wrapper">
    63. <canvas id="canvas"></canvas>
    64. <div id="controller">
    65. <h1>Canvas 绘图之旅</h1>
    66. <a href="#" id="canvas-btn">停止运动</a>
    67. <a href="#" class="color-btn" id="white-color-btn">&nbsp;</a>
    68. <a href="#" class="color-btn" id="black-color-btn">&nbsp;</a>
    69. </div>
    70. </div>
    71. <script>
    72. const canvas = document.getElementById('canvas')
    73. canvas.width = 1200
    74. canvas.height = 800
    75. const context = canvas.getContext('2d')
    76. const balls = []
    77. let isMoving = true
    78. let themeColor = 'white'
    79. for(let i = 0; i < 100; i++) {
    80. const R = Math.floor(Math.random() * 255)
    81. const G = Math.floor(Math.random() * 255)
    82. const B = Math.floor(Math.random() * 255)
    83. const radius = Math.random() * 50 + 20
    84. const ball = {
    85. color: `rgb(${R}, ${G}, ${B})`,
    86. radius,
    87. x: Math.random() * (canvas.width - 2*radius) + radius,
    88. y: Math.random() * (canvas.height - 2*radius) + radius,
    89. vx: (Math.random() * 5 + 5) * Math.pow(-1, Math.floor(Math.random()*100)),
    90. vy: (Math.random() * 5 + 5) * Math.pow(-1, Math.floor(Math.random() * 100)),
    91. }
    92. balls[i] = ball
    93. }
    94. setInterval(function() {
    95. draw(context)
    96. if(isMoving) {
    97. update(canvas.width, canvas.height)
    98. }
    99. }, 50)
    100. document.getElementById('canvas-btn').onclick = function() {
    101. if (isMoving) {
    102. isMoving = false
    103. this.text = '开始运动'
    104. } else {
    105. isMoving = true
    106. this.text = '停止运动'
    107. }
    108. }
    109. document.getElementById('white-color-btn').onclick = function() {
    110. themeColor = 'white'
    111. return false
    112. }
    113. document.getElementById('black-color-btn').onclick = function () {
    114. themeColor = 'black'
    115. return false
    116. }
    117. function draw(cxt) {
    118. cxt.clearRect(0, 0, cxt.canvas.width, cxt.canvas.height)
    119. if (themeColor === 'black') {
    120. cxt.fillStyle = 'black'
    121. cxt.fillRect(0, 0, cxt.canvas.width, cxt.canvas.height)
    122. }
    123. for(let i = 0; i < balls.length; i++) {
    124. cxt.fillStyle = balls[i].color
    125. cxt.beginPath()
    126. cxt.arc(balls[i].x, balls[i].y, balls[i].radius, 0, Math.PI*2)
    127. cxt.closePath()
    128. cxt.fill()
    129. }
    130. }
    131. function update(canvasWidth, canvasHeight) {
    132. for (let i = 0; i < balls.length; i++) {
    133. balls[i].x += balls[i].vx
    134. balls[i].y += balls[i].vy
    135. if (balls[i].x - balls[i].radius <= 0) {
    136. balls[i].vx = -balls[i].vx
    137. balls[i].x = balls[i].radius
    138. }
    139. if (balls[i].x + balls[i].radius >= canvasWidth) {
    140. balls[i].vx = -balls[i].vx
    141. balls[i].x = canvasWidth - balls[i].radius
    142. }
    143. if (balls[i].y - balls[i].radius <= 0) {
    144. balls[i].vy = -balls[i].vy
    145. balls[i].y = balls[i].radius
    146. }
    147. if (balls[i].y - balls[i].radius >= canvasHeight) {
    148. balls[i].vy = -balls[i].vy
    149. balls[i].y = canvasHeight - balls[i].radius
    150. }
    151. }
    152. }
    153. </script>
    154. </body>
    155. </html>

    图示:

    刮刮乐

    1. <!DOCTYPE html>
    2. <html lang="en" style="height:100%;">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <title>Document</title>
    7. </head>
    8. <body style="height:100%;">
    9. <canvas id="canvas" style="border: 1px solid #aaa;display:block;margin: 20px auto;"></canvas>
    10. <script>
    11. const canvas = document.getElementById('canvas')
    12. canvas.width = 1152
    13. canvas.height = 768
    14. const ctx = canvas.getContext('2d')
    15. // 绘制底部显示中奖区域
    16. const arr = ["img2.png"]
    17. const number = Math.floor(Math.random() * arr.length)
    18. canvas.style.background = "url(" + arr[number] + ")"
    19. canvas.style.backgroundSize = "100%"
    20. // 绘制遮盖区域
    21. const image = new Image()
    22. image.src = "img1.png"
    23. image.onload = function () {
    24. ctx.drawImage(image, 0, 0, canvas.width, canvas.height)
    25. ctx.font = 'bold 40px PingFang SC'
    26. ctx.fillStyle = '#C96048'
    27. ctx.textAlign = 'center'
    28. ctx.textBaseline = 'middle'
    29. ctx.fillText('刮刮我,有惊喜~', 576, 384)
    30. }
    31. let status = false
    32. canvas.onmousedown = function (e) {
    33. e.preventDefault()
    34. status = true
    35. }
    36. canvas.onmouseup = function (e) {
    37. e.preventDefault()
    38. status = false
    39. }
    40. canvas.onmousemove = function (e) {
    41. e.preventDefault()
    42. if (status == true) {
    43. const x = e.clientX - canvas.getBoundingClientRect().left
    44. const y = e.clientY - canvas.getBoundingClientRect().top
    45. ctx.globalCompositeOperation = "destination-out"
    46. ctx.beginPath()
    47. ctx.arc(x, y, 20, 0, 2 * Math.PI)
    48. ctx.closePath()
    49. ctx.fill()
    50. const rate = getFilledPercentage()
    51. console.log(rate)
    52. if (rate > 60) {
    53. ctx.clearRect(0, 0, canvas.width, canvas.height)
    54. }
    55. }
    56. }
    57. // 计算已经刮过的区域占整个区域的百分比
    58. function getFilledPercentage() {
    59. const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height)
    60. // imgData.data是个数组,存储着指定区域每个像素点的信息,数组中4个元素表示一个像素点的rgba值
    61. const pixels = imgData.data
    62. const transPixels = []
    63. for (let i = 0; i < pixels.length; i += 4) {
    64. // 严格上来说,判断像素点是否透明需要判断该像素点的a值是否等于0
    65. // 为了提高计算效率,这儿设置当a值小于128,也就是半透明状态时就可以了
    66. if (pixels[i + 3] < 128) {
    67. transPixels.push(pixels[i + 3])
    68. }
    69. }
    70. return (transPixels.length / (pixels.length / 4) * 100).toFixed(2)
    71. }
    72. </script>
    73. </body>
    74. </html>

    图示:

    2

    1

  • 相关阅读:
    吃透Redis(七):网络框架篇-redis 6.0 IO多线程原子性保证
    剖析一下“抢茅台“脚本底层逻辑
    为什么Netty NioEventLoopGroup的线程数默认为CPU核心数_2?
    基于spring boot的医疗管理系统 /基于java的医疗系统
    React 的学习笔记
    领航未来,2022 世界人工智能大会「元宇宙的数字原生进化」论坛等你来!
    关于CPP类中字符串成员初始化
    可持续化线段树(主席树)几种用法总结
    集群、分布式、微服务的区别和介绍
    java面试题ConcurrentHashMap 的工作原理及代码实现
  • 原文地址:https://blog.csdn.net/m0_38066007/article/details/134028483