在保留图像的同时在 HTML5 Canvas 中绘制图像

新手上路,请多包涵

在 HTML5 Canvas 中,在图像(已经在画布上)上绘制 和移动 线条并保留下方图像的最简单方法是什么? (例如,有一条垂直线跟踪鼠标 X 位置)

我目前的画布:

 $(document).ready(function() {
  canvas = document.getElementById("myCanvas");
  context = canvas.getContext("2d");
  imageObj = new Image();

    imageObj.onload = function() {
    context.drawImage(imageObj, 0,0);
  }
  imageObj.src = "http://example.com/some_image.png";
  $('#myCanvas').click(doSomething);
});

原文由 Asaf Bartov 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 308
2 个回答

您将必须使用画布完成大部分基础工作,在这种情况下,您将必须实现移动线条的功能,然后重新绘制所有内容。

步骤可以是:

  • 将线保留为可以自渲染的对象(对象上的方法)
  • 听 mousemove(在这种情况下)以移动线
  • 对于每次移动,重新绘制背景(图像)然后在新位置渲染线

您可以重新绘制整个背景,也可以对其进行优化以仅绘制最后一行。

这是一些示例代码和 现场演示

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

现在我们需要做的就是有一个机制来更新每一步的背景和线条:

 /// updates the line on each mouse move
function updateLine(e) {

    /// correct mouse position so it's relative to canvas
    var r = canvas.getBoundingClientRect(),
        x = e.clientX - r.left,
        y = e.clientY - r.top;

    /// draw background image to clear previous line
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

    /// update line object and draw it
    line.x1 = x;
    line.y1 = 0;
    line.x2 = x;
    line.y2 = canvas.height;
    line.draw();
}

自定义线对象在这个演示中非常简单:

 /// This lets us define a custom line object which self-draws
function Line(ctx) {

    var me = this;

    this.x1 = 0;
    this.x2 = 0;
    this.y1 = 0;
    this.y2 = 0;

    /// call this method to update line
    this.draw = function() {
        ctx.beginPath();
        ctx.moveTo(me.x1, me.y1);
        ctx.lineTo(me.x2, me.y2);
        ctx.stroke();
    }
}

如果您不打算对图像本身做任何特定的事情,您也可以使用 CSS 将其设置为背景图像。不过,在重新绘制线条之前,您仍然需要清除画布。

原文由 user1693593 发布,翻译遵循 CC BY-SA 3.0 许可协议

可能这不是一个实际的答案,以防万一您需要它(将来)。使用某些库使用画布会更好(也更容易)。我已经尝试过 CreateJS 的 EaselJS 并发现自己喜欢它。你可以看看它 EaselJS (我已经做了一个例子,允许使用 EaselJS 绘制和拖动图像很久以前)

原文由 Shinigamae 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题