【问题标题】:Display canvas shape always on top of another shape始终在另一个形状之上显示画布形状
【发布时间】:2018-02-21 00:23:41
【问题描述】:

我的画布中有两个移动的矩形,一个是绿色的,一个是红色的。当它们在同一位置并且您只能看到其中一个时,始终显示红色矩形,而绿色矩形只是在红色矩形下方。

如何实现绿色始终显示在顶部?

【问题讨论】:

    标签: javascript html canvas html5-canvas


    【解决方案1】:

    没有任何代码很难说,但如果你先有绿色矩形的代码,它将首先绘制,红色将绘制在它上面。

    【讨论】:

    • 谢谢,现在看来合乎逻辑:)
    【解决方案2】:

    我认为你应该在涂红色之后再涂绿色。所以如果你的矩形在一个数组中,你可以以相反的顺序迭代它

    (function start() {
      const canvas = document.getElementById('canvas');
      canvas.width = window.innerWidth || $(window).width();
      canvas.height = window.innerHeight || $(window).height();
      const ctx = canvas.getContext('2d');
    
      const draw = function(opts={color: 'yellow', x: 0, y: 0}) {
        ctx.beginPath();
        ctx.rect(opts.x, opts.y, 150, 100);
        ctx.fillStyle = opts.color;
        ctx.fill();
      }
    
      // COLUMN 1
      draw({color: 'red',x: 20,y: 20});
      draw({color: 'green',x: 40,y: 40});
      
      // COLUMN 2
      draw({color: 'green', x: 200, y: 20});
      draw({color: 'red', x: 220, y: 40});
    })();
    html,
    body {
      height: 100%;
      width: 100%;
      margin: 0;
      padding: 0;
      background: #000;
    }
    
    canvas {
      position: absolute;
      left: 0;
      top: 0;
      z-index: 0;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <canvas id='canvas'></canvas>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多