如何在图像上方制作画布线图?

时间:2016-02-12 05:33:15

标签: html css html5-canvas z-index

基本上,我正在创建一个匹配的游戏。当我选择一个项目(例如图中所示的梨)时,它会向右翻译。但是,它最终将位于画布上绘制的线上。我希望线条位于图像的顶部,而不是反过来。

我尝试使用z-index for canvas比img更大但它不起作用。知道如何解决这个问题吗?

enter image description here

HTML

<table class="first">
  <tr>
    <td>
      <ul class="firstleft">
      /*some images to be filled here*/
      </ul>
    </td>
    <td>
      <canvas id="myCanvas" resize></canvas>
    </td>
    <td>
      <ul class="firstright">
      /*some images to be filled here*/
      </ul>
    </td>
  </tr>
</table>

CSS

img {
   z-index: 1;
}
canvas {
   z-index: 20;
}

JS

var canvas = document.getElementById('myCanvas');
ctx = canvas.getContext("2d")
ctx.lineWidth = 6;
ctx.strokeStyle = "#333";
/* Drawing part using an example*/
ctx.beginPath();
ctx.moveTo(100, 250);
ctx.bezierCurveTo(150, 100, 350, 100, 400, 250);
ctx.stroke();

1 个答案:

答案 0 :(得分:0)

在这种情况下它起作用

var canvas = document.getElementById('demo'), /// canvas element
    ctx = canvas.getContext('2d'),            /// context
    line = new Line(ctx),                     /// our custom line object
    img = new Image;                          /// the image for bg

ctx.strokeStyle = '#fff';                     /// white line for demo

/// start image loading, when done draw and setup 
img.onload = start;
img.src = 'http://i.imgur.com/O712qpO.jpg';

function start() {
    /// initial draw of image
    ctx.drawImage(img, 0, 0, demo.width, demo.height);

    /// listen to mouse move (or use jQuery on('mousemove') instead)
    canvas.onmousemove = updateLine;
}