绘制矩形

  1. var canvas = document.getElementsByClassName('canvas')[0];
  2. var ctx = canvas.getContext('2d');
  3. ctx.lineWidth = 10;
  4. ctx.moveTo(100,100);
  5. ctx.lineTo(300,100)
  6. ctx.lineTo(300,200)
  7. ctx.lineTo(100,200)
  8. ctx.closePath()
  9. ctx.stroke()

效果图
image.png

rect()绘制矩形

  1. ctx.rect(100,100,200,100);
  2. ctx.fill()
  3. ctx.stroke()

效果图
image.png

矩形框

  1. ctx.strokeRect(100,100,200,100);

效果图
image.png

填充矩形

  1. ctx.fillRect(100,100,200,100)

效果图
image.png
demo 模拟重力

  1. <body>
  2. <canvas class="canvas" width="500" height="500" style="width: 500px; height: 500px; border: 1px solid #000;"></canvas>
  3. <script>
  4. var canvas = document.getElementsByClassName('canvas')[0];
  5. console.log(canvas)
  6. var ctx = canvas.getContext('2d');
  7. var boxTop = 10;
  8. var boxLeft = 10;
  9. var boxWidth = 50;
  10. var boxHeight = 50;
  11. var speedX = 1;
  12. var speedY = 1;
  13. var gravity = 1;
  14. var timer = null;
  15. ctx.fillRect(boxLeft, boxTop, boxWidth, boxHeight)
  16. function move() {
  17. var num = 0;
  18. timer = setInterval(() => {
  19. speedY = speedY + gravity
  20. boxTop += speedY;
  21. boxLeft += speedX;
  22. if (boxTop <= 0) {
  23. speedY *= -1;
  24. speedX *= 0.8;
  25. speedY *= 0.8;
  26. }
  27. if (boxTop >= 450) {
  28. speedY *= -1;
  29. speedX *= 0.6;
  30. speedY *= 0.6;
  31. boxTop = 450;
  32. num++;
  33. var time = new Date().getTime()
  34. }
  35. if (boxLeft <= 0) {
  36. speedX *= -1;
  37. speedX *= 0.8;
  38. speedY *= 0.8;
  39. }
  40. if (boxLeft >= 450) {
  41. speedX *= -1;
  42. speedX *= 0.8;
  43. speedY *= 0.8;
  44. boxLeft = 450;
  45. }
  46. if (num > 10 && (new Date().getTime() - time) < 500 ) {
  47. clearInterval(timer)
  48. } else {
  49. ctx.clearRect(0, 0, 500, 500)
  50. ctx.fillRect(boxLeft, boxTop, boxWidth, boxHeight)
  51. }
  52. console.log(speedX + "::::" + speedY + "::::" + boxLeft + "::::" + boxTop)
  53. }, 100);
  54. }
  55. move()
  56. </script>
  57. </body>