我正在使用fabricjs将图像放在画布上。我想知道我需要做些什么才能用url onclick中的另一个替换已经绘制的图像。
我有限的理解让我觉得我需要为每个图像设置一个var,但我不确定如何将它与fabricjs画布连接起来。我花了最后几个小时尝试不同的东西而没有任何运气。
我尝试提交类似的问题,但删除了它,因为我觉得这可能是一个太复杂的问题。任何帮助将不胜感激。这是我现在的代码:
var canvas = new fabric.Canvas('c');
fabric.Image.fromURL('http://lorempixel.com/400/400/', function(img) {
var oImg = img.set({
selectable: false
})
canvas.add(oImg).renderAll();
});
canvas {
border: 1px solid #dddddd;
border-radius: 3px;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<canvas id="c" width="400" height="400"></canvas>
答案 0 :(得分:2)
你可以做得更简单。不知道为什么你会为这样的事情使用额外的lib。我用简单的JS写了一些小东西,希望能进一步帮助你。
-Werror
&#13;
document.getElementById("image").onclick = function(){
document.getElementById("image").src = "http://lorempixel.com/400/400/";
};
&#13;
答案 1 :(得分:2)
这就是你如何实现这个目标:
var canvas = new fabric.Canvas('c');
var image, isImageLoaded;
fabric.Image.fromURL('//lorempixel.com/200/200/', function(img) {
isImageLoaded = true;
image = img.set({
selectable: false
})
canvas.add(image).renderAll();
});
function replaceImage(imgUrl) {
if (!isImageLoaded) return; //return if initial image not loaded
var imgElem = image._element; //reference to actual image element
imgElem.src = imgUrl; //set image source
imgElem.onload = () => canvas.renderAll(); //render on image load
}
canvas.on('mouse:down', function() {
replaceImage('//lorempixel.com/200/200/');
});
&#13;
canvas {
border: 1px solid #dddddd;
border-radius: 3px;
}
&#13;
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<canvas id="c" width="200" height="200"></canvas>
&#13;
PS:道歉没有给出那么多解释。
答案 2 :(得分:1)
var canvas = new fabric.Canvas('c');
var oImg;
loadImage();
function loadImage(){
fabric.Image.fromURL('https://lorempixel.com/400/400/', function(img) {
oImg && canvas.remove(oImg); //If image element alread added to canvas remove it.
oImg = img.set({
selectable: false
})
canvas.add(oImg); //add new image to canvas
oImg.on('mousedown',onImgMouseDown); //add mouse down lisner to image
});
}
function onImgMouseDown(){
loadImage();
}
&#13;
canvas {
border: 1px solid #dddddd;
border-radius: 3px;
}
&#13;
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<canvas id="c" width="400" height="400"></canvas>
&#13;
备选您将mousedown侦听器添加到图像,并检查是否添加了元素,然后将其从画布中删除。然后在画布上添加新的。