11

In HTML5 Canvas, what's the simplest way to draw and move a line over an Image (already on the canvas), preserving the image underneath? (e.g. have a vertical line track the mouse X position)

My current canvas:

$(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);
});
4

4 回答 4

18

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

步骤可以是:

  • 将线条保持为可以自渲染的对象(对象上的方法)
  • 听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 将其设置为背景图像。不过,在重新绘制线条之前,您仍然需要清除画布。

于 2013-11-14T00:03:09.243 回答
3

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

于 2013-11-14T02:10:17.587 回答
3

您可以通过监听 mousemove 事件来获得“十字准线”,然后:

  • 清除画布
  • 绘制图像
  • 在鼠标位置画线

这是代码和小提琴:http: //jsfiddle.net/m1erickson/jEc7N/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; padding:20px; }
    #canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    ctx.lineWidth=2;

    var canvasOffset=$("#canvas").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;

    var img=new Image();
    img.onload=function(){
        canvas.width=img.width;
        canvas.height=img.height;
        ctx.drawImage(img,0,0);

    }
    img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/KoolAidMan.png";

    function handleMouseMove(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);

      ctx.clearRect(0,0,canvas.width,canvas.height);
      ctx.drawImage(img,0,0);
      ctx.beginPath();
      ctx.moveTo(mouseX,0);
      ctx.lineTo(mouseX,canvas.height);
      ctx.moveTo(0,mouseY);
      ctx.lineTo(canvas.width,mouseY);
      ctx.stroke();


    }

    $("#canvas").mousemove(function(e){handleMouseMove(e);});


}); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
于 2013-11-14T00:22:29.803 回答
2

或者只使用2 层

  1. 背景层有图像并且不改变,
  2. 顶层有线条,你可以清除和重绘很多时间而不影响背景层。
于 2013-11-14T09:28:19.943 回答