【问题标题】:Canvas Drawing on Draggable Images可拖动图像上的画布绘图
【发布时间】:2023-03-30 07:55:01
【问题描述】:

在具有一些可拖动图像的 html 页面上,我们必须使用鼠标指针绘制形状或线条,绘制图像和形状已完成,但不能在可拖动图像上。此外,如果用户移动图像,则之前绘制的形状应该保留
他们的。同时,我已经能够创建形状和画线,但是当我尝试画线时
在图像上它会回到背景。有人可以建议我如何使用
canvas 和 html5,目前也在使用。

【问题讨论】:

    标签: html html5-canvas html5-draggable


    【解决方案1】:

    一种方法是创建一个函数来绘制您的图像和与该图像关联的形状

    您可以通过使用与图像偏移相同的偏移量绘制形状来保持图像及其形状的协调。因此,如果您在 [x,y] 处绘制图像,那么您会将 x 和 y 添加到形状中的每个点:

    // points[] is an array of points that defines the shape you
    // want drawn on your image
    
    function drawImageWithShapes(img,points,x,y){
        ctx.drawImage(img,x,y);
        ctx.beginPath();
        ctx.moveTo(points[0].x+x,points[0].y+y);
        for(var i=1; i<points.length;i++){
            ctx.lineTo(points[i].x+x,points[i].y+y);
        }
        ctx.stroke();
    }
    

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var cw=canvas.width;
    var ch=canvas.height;
    
    ctx.lineWidth=4;
    ctx.strokeStyle='red';
    
    var x=50;
    var y=50;
    
    var points=[];
    points.push({x:37,y:0});
    points.push({x:75,y:75});
    points.push({x:0,y:75});
    points.push({x:37,y:0});
    
    
    var img=new Image();
    img.onload=start;
    img.src="https://dl.dropboxusercontent.com/u/139992952/multple/sun.png";
    function start(){
      drawImageWithShapes(img,points,x,y);
    }
    
    function drawImageWithShapes(img,points,x,y){
      ctx.drawImage(img,x,y);
      ctx.beginPath();
      ctx.moveTo(points[0].x+x,points[0].y+y);
      for(var i=1; i<points.length;i++){
        ctx.lineTo(points[i].x+x,points[i].y+y);
      }
      ctx.stroke();
    }
    
    $('#test').click(function(){
      x+=10;
      y+=10;
      ctx.clearRect(0,0,cw,ch);
      drawImageWithShapes(img,points,x,y);
    
    });
    body{ background-color: ivory; padding:10px; }
    #canvas{border:1px solid red;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <button id=test>Move and Redraw</button><br><br>
    <canvas id="canvas" width=300 height=300></canvas>

    【讨论】:

    • 似乎接近我正在寻找的东西,我们可以在运行时而不是加载时使用鼠标指针在图像上绘制线条,然后将图像与绘制线一起拖动。?
    • @NewBee。当然......有很多很多使用鼠标在html5画布上画线的例子,所以我不再在这里说明了。这是许多示例之一的链接:stackoverflow.com/questions/23140642/…。祝你的项目好运!
    • 感谢您的快速回复。但是,ill try to explain the problem again. There are some images on page which are draggable and now what i want is ill 在该可拖动图像上标记圆圈。所以,如果我现在拖动图像,标记它的圆圈也会被拖动。我希望我现在能够解释它....谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-07
    相关资源
    最近更新 更多