在 HTML5 画布中绘制图像,同时保留图像

drawing over an Image in HTML5 Canvas while preserving the image

本文关键字:图像 保留 绘制 HTML5 布中      更新时间:2023-09-26

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

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

步骤可以是:

  • 将线条保留为可以自我渲染的对象(对象上的方法)
  • 听鼠标移动(在本例中)以移动行
  • 对于每次移动,重绘背景(图像),然后在新位置渲染线条

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

下面是一些示例代码和此处的现场演示

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将其设置为背景图像。不过,在重新绘制线条之前,您仍然需要清除画布。

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

您可以通过侦听鼠标移动事件来获取"十字准线",然后:

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

这是代码和小提琴: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>

或者只使用 2 层

  1. 背景层有图像,不会改变,
  2. 顶层有线条,您可以清除并重绘大量时间而不影响背景图层。