I am currently working on the following project: I am uploading a picture from my computre which I then show on my page on a canvas. Now all I want to do is, draw some rectangles on the picture and get the coordinates of those.
However, it seems that the rectangles I draw are somehow behind the background picture. I can see (in the console) that the created div is inside the canvas (the rectangle) but it is not shown on the background image. I tried to change the z-index but that does not seem to help.
Does anyone know what I am doing wrong? Does that even work that way?
(I got the rectangle drawing code from here)
This is my code so far (ts):
export class AppComponent {
title = 'app';
public buildings = [ ];
public showUploader = true;
constructor() { }
public getImages() {
this.buildings = document.getElementById('imageImport')['files'];
const reader = new FileReader();
reader.onload = function (e) {
const canvas: any = document.getElementById('imageCanvas');
const ctx = canvas.getContext('2d');
const img: any = new Image();
img.onload = function () {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
};
img.src = e.target['result'];
};
reader.readAsDataURL(this.buildings[0]);
this.showUploader = false;
this.initDraw(document.getElementById('imageCanvas'));
}
public initDraw(canvas) {
function setMousePosition(e) {
const ev = e || window.event;
if (ev.pageX) {
mouse.x = ev.pageX + window.pageXOffset;
mouse.y = ev.pageY + window.pageYOffset;
} else if (ev.clientX) {
mouse.x = ev.clientX + document.body.scrollLeft;
mouse.y = ev.clientY + document.body.scrollTop;
}
}
const mouse = {
x: 0,
y: 0,
startX: 0,
startY: 0
};
let element = null;
canvas.onmousemove = function (e) {
setMousePosition(e);
if (element !== null) {
element.style.width = Math.abs(mouse.x - mouse.startX) + 'px';
element.style.height = Math.abs(mouse.y - mouse.startY) + 'px';
element.style.left = (mouse.x - mouse.startX < 0) ? mouse.x + 'px' : mouse.startX + 'px';
element.style.top = (mouse.y - mouse.startY < 0) ? mouse.y + 'px' : mouse.startY + 'px';
}
};
canvas.onclick = function (e) {
if (element !== null) {
element = null;
canvas.style.cursor = 'default';
console.log('finsihed.');
} else {
console.log('begun.');
mouse.startX = mouse.x;
mouse.startY = mouse.y;
element = document.createElement('div');
element.className = 'rectangle';
element.style.left = mouse.x + 'px';
element.style.top = mouse.y + 'px';
canvas.appendChild(element);
canvas.style.cursor = 'crosshair';
}
};
}
}
and the html:
<input id="imageImport" type="file" multiple="multiple" (change)=getImages() *ngIf="showUploader"/>
<div>
<canvas id="imageCanvas"> </canvas>
</div>