在背景中我有图像,这里我需要在图像上使用特定坐标(它们来自API)绘制一个矩形。 由于坐标不断变化,如何动态绘制。
我尝试过使用canvas、svg,但不起作用。上一个问题的链接 How to draw svg on image?
坐标:
var a = _self.sendObjCoordinates[0].coordinates.xmin;
var b = _self.sendObjCoordinates[0].coordinates.ymin;
var c = _self.sendObjCoordinates[0].coordinates.xmax;
var d = _self.sendObjCoordinates[0].coordinates.ymax;
样本值:
{xmin: 399, ymin: 191, xmax: 1166, ymax: 742}
1)加载图片代码:
<div class="lbi-svg-box scrollbar-external">
<img src="" alt="" class="lbi-img" />
<svg class="lbi-svg">
</svg>
</div>
2)我在这里创建 Canvas
Labelimg.prototype = {
addImg: function (src) {
var img = document.querySelector('.lbi-img');
if (!img) {
var canvas = document.createElement('canvas');
img = document.createElement('img');
img.className = 'lbi-img';
canvas.id = "CursorLayer";
canvas.width = 500;
canvas.height = 700;
}
}
}
The error is :Uncaught TypeError: Cannot read property 'getContext' of null
at HTMLButtonElement.submitFormBtn.onclick (labelimg.js:418)
3)创建矩形的代码:
var can = document.getElementById("CursorLayer");
var ctx = can.getContext('2d');
ctx.fillStyle='#fa4b2a'; // color of fill
ctx.rect(20, 20, 150, 100);
ctx.stroke(); // create rectangle
最佳答案
您尝试在您使用的 Canvas 上绘制矩形的时间 getElementyById() 函数来获取对 Canvas 的引用。 不幸的是它会返回 null 因为你实际上并没有将 Canvas 添加到 DOM - 因此它不存在并且你得到:
Cannot read property 'getContext' of null
将动态创建的 HTML 元素添加到 DOM 是通过 appendChild() 函数完成的。
尝试改变:
var canvas = document.createElement('canvas');
至:
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
关于javascript - 如何使用从后端/API 获得的特定坐标绘制矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59088519/