0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Matter.jsとCanvasを重ねる

Posted at

使いどころ

Matter.jsでアニメーションやゲームを作った上に物理演算とは関係ない文字・画像をCanvasで表示したい時

HTML

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" type="text/css" href="style.css">
    <title>Document</title>
</head>
<body>
    <canvas id="world"></canvas>
    <canvas id="overlay"></canvas>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.10.0/matter.min.js"></script>
    <script src="main.js"></script>

</body>
</html>

  • canvasを2枚用意して別のID("world", "overlay")を付けます

CSS

style.css
canvas {
  position: absolute;
}
# overlay {
  background-color: transparent;
}
  • canvasにposition:absoluteを指定することで、2つ重ねて表示することができます
    (absoluteを指定しないと2枚のcanvasが横に並んでしまう)
  • 前面のキャンバス(#overlay)の背景を透明にすることでオーバーレイできます

JS

main.js
  // 前面キャンバス (id="overlay") 箱を置くだけ
(function() {
  'use strict';

  var stage = document.getElementById('overlay');
  var ctx;

  if (typeof stage.getContext === 'undefined') {
    return;
  }
  ctx = stage.getContext('2d');

  stage.width = 600;
  stage.height = 600;

  ctx.strokeRect(300, 300, 100, 60);

})();

  // 背面キャンバス (id="world") 玉が地面に落下するだけ
  var Engine = Matter.Engine,
      Render = Matter.Render,
      World = Matter.World,
      Bodies = Matter.Bodies;

  var engine = Engine.create(),
      world = engine.world;

  var winWidth = 600;
  var winHeight = 600;

  var canvas = document.getElementById('world');

  var render = Render.create({
      canvas: canvas,
      engine: engine,
      options: {
        width: winWidth,
        height: winHeight,
        background: '#8bc2c9',
        wireframes: false
      }
  });

  // 玉
  var boxA = Bodies.circle(300, 200, 40, {
    render: {
      fillStyle: 'white',
      strokeStyle: 'transparent'
    }
  });

  // 地面
  var ground = Bodies.rectangle(winWidth/2, winHeight, winWidth, 10, {
    isStatic: true,
    render: {
      fillStyle: 'white',
      strokeStyle: 'transparent'
    }
  });

  World.add(engine.world, [boxA, ground]);
  Engine.run(engine);
  Render.run(render);

qiita.gif

参考記事

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?