【问题标题】:Clone canvas with fabric js and continue editing用fabric js克隆画布并继续编辑
【发布时间】:2017-03-19 07:05:08
【问题描述】:

我想用织物 js 克隆画布并继续在克隆画布中编辑现有的织物 js 对象,但它不起作用。它表明 setBackgroundImage 未定义。

$('#btnClick').on('click touchstart', function () {
    var canvas = document.getElementsByTagName("canvas");
    // canvas context
    var context = canvas[0].getContext("2d");
    // get the current ImageData for the canvas
    var data = context.getImageData(0, 0, canvas[0].width, canvas[0].height);
    // store the current globalCompositeOperation
    var compositeOperation = context.globalCompositeOperation;
    // set to draw behind current content
    context.globalCompositeOperation = "destination-over";
    //set background color
    context.fillStyle = "#FFFFFF";
    // draw background/rectangle on entire canvas
    context.fillRect(0,0,canvas[0].width,canvas[0].height);

    var tempCanvas = document.createElement("canvas"),
    tCtx = tempCanvas.getContext("2d");
    
    tempCanvas.width = 640;
    tempCanvas.height = 480;
  
    tempCanvas.setBackgroundImage('');
}
<canvas><canvas>

【问题讨论】:

  • javascript 画布没有任何 setBackgroundImage api。可能你应该通过创建它来使用这个画布的织物对象
  • 虽然你可以通过 css canvas { background:url(img.jpg) }为画布添加背景

标签: javascript canvas fabricjs


【解决方案1】:

使用织物库的想法是使用它的方法来简化您的工作。您不会直接与画布元素交互。

canvas loadFromJSONtoJSON 方法可用于克隆包含背景图像的画布副本。

var canvas = new fabric.Canvas('canvas');
var canvas2 = new fabric.Canvas('canvas2');
$(document).ready(function() {
    var rect = new fabric.Rect({width: 100, height:200, fill: 'red'});
    canvas.add(rect);
    var circle = new fabric.Circle({radius: 80, fill: 'blue'});
    canvas.add(circle);        
    $('#clone').click(
      function(){canvas2.loadFromJSON(JSON.stringify(canvas), function(){canvas2.renderAll()}); })
});
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
   
<canvas id='canvas' width="500" height="400" style="border:#000 1px solid;">
</canvas>
 <input id="clone" type="button" value="clone canvas">
<canvas id='canvas2' width="500" height="400" style="border:#000 1px solid;">
</canvas>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-20
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多