【问题标题】:How to make canvas line drawings above image?如何在图像上方制作画布线条图?
【发布时间】:2016-05-23 04:22:15
【问题描述】:

基本上,我正在创建一个匹配游戏。当我选择一个项目(例如图片中的梨)时,它会向右平移。但是,它最终会出现在画布上绘制的线条之上。我希望线条位于图像顶部,而不是相反。

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

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();

【问题讨论】:

  • image z-index 设置为 -1
  • 嗯。还是不行
  • 看看这个...可能对你有帮助 ..stackoverflow.com/questions/10623678/… 这个也是stackoverflow.com/questions/26902084/…
  • 图像的 z-index 应为 -1,行 z-index 应为 1
  • @AkshayKumar 好吧,我认为在这种情况下有所不同,因为我不是在图像上绘图。我在画布上画线,我正在翻译恰好碰到线的图像。如果我错了,请纠正我

标签: html css html5-canvas z-index


【解决方案1】:

在这种情况下它可以工作

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;
}

【讨论】:

    猜你喜欢
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    • 2011-09-30
    • 1970-01-01
    • 2012-04-20
    • 2012-07-09
    • 1970-01-01
    相关资源
    最近更新 更多