【发布时间】:2021-01-17 05:29:45
【问题描述】:
我在动态创建和设置画布背景时遇到问题。 我希望用户能够用文本和形状注释图像,这就是我这样做的原因。
我想知道为什么这段代码会产生这样的输出
想法
- 向端点发送获取请求,该端点返回包含的 json 数据 图片网址。
- 将该数据转换为 javascript 数组。
- 根据上面的长度动态创建fabric js画布 数组。
- 使用它们的 url 将画布背景设置为图像。 (即每个画布将具有从 url 获取的不同背景)
问题
只有最后一个画布有背景图片。
代码
<!DOCTYPE html>
<html>
<head>
<style>
body {
}
</style>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"
></script>
</head>
<body>
<script src="fabric.js"></script>
<!--new start-->
<script>
//procedurally load images from a given source
//endpoint with image links
var end_point = "http://localhost:8080/endpoint.php";
var settings = {
url: "http://localhost:8080/endpoint.php",
method: "GET",
};
//get the images array from end point
$.ajax(settings).done(function (images_json) {
var images = JSON.parse(images_json);
//procedurally create farbric.js canvas for each image element in the html document and set their background as the corresponding image.
//for each item in the images array, create a fabric.js canvas with its background set as the image itself
var canvas_array = [];
for (var i = 0, len = images.length; i < len; i++) {
//console.log(images[i]);
//create canvas and then make it a fabric canvas
document.body.innerHTML += `<canvas
id=${[i]}
width="1000"
height="200"
style="border-style: solid;">
</canvas>`;
//canvases stored in canvas_array
canvas_array[i] = new fabric.Canvas(`${[i]}`);
console.log(canvas_array[i]);
//set canvas background as the image
canvas_array[i].setBackgroundImage(
`${images[i]}`,
canvas_array[i].renderAll.bind(canvas_array[i]),
{
backgroundImageOpacity: 1,
backgroundImageStretch: false,
}
);
}
});
</script>
<!--new end-->
</body>
</html>
结果
注意 该代码正在生成正确数量的画布。但是背景图像似乎不起作用
期望的结果将有 10 个不同背景的画布,对应于图像 url。
我是 fabric.js 的新手,这可能是一个愚蠢的错误。
【问题讨论】:
标签: javascript html fabricjs