var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var rect = {};
var drag = false;
var storeRects = [];
var isMoving = false;
make_base();
init();
function make_base() {
base_image = new Image();
base_image.src = 'https://www.w3schools.com/css/img_fjords.jpg';
base_image.onload = function() {
context.drawImage(base_image, 0, 0, 800, 500);
}
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function init() {
canvas.addEventListener('mousedown', mouseDown, false);
canvas.addEventListener('mouseup', mouseUp, false);
canvas.addEventListener('mousemove', mouseMove, false);
}
function mouseDown(e) {
rect.startX = e.pageX - this.offsetLeft;
rect.startY = e.pageY - this.offsetTop;
drag = true;
}
function mouseMove(e) {
if(drag) {
isMoving = true;
rect.w = (e.pageX - this.offsetLeft) - rect.startX;
rect.h = (e.pageY - this.offsetTop) - rect.startY ;
draw();
}
}
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(base_image, 0 ,0, 800, 500);
storeRects.forEach(function(rect) {
context.beginPath();
context.rect(rect.x, rect.y,rect.w, rect.h);
context.stroke();
});
context.lineWidth="1";
context.strokeStyle = "red";
context.beginPath();
context.rect(rect.startX, rect.startY, rect.w, rect.h);
context.stroke();
}
function mouseUp() {
drag = false;
if(isMoving === true) {
storeRects.push({
x: rect.startX,
y: rect.startY,
w: rect.w,
h: rect.h,
});
var c = document.getElementById("myCanvasPreview");
var ctx = c.getContext("2d");
var pre_base_image = new Image();
pre_base_image.src = 'https://www.w3schools.com/css/img_fjords.jpg';
ctx.drawImage(pre_base_image,
(Math.min(storeRects[0].x, storeRects[0].x + Math.abs(storeRects[0].w))/canvas.width) * pre_base_image.width,
(Math.min(storeRects[0].y, storeRects[0].y + Math.abs(storeRects[0].h))/canvas.height) * pre_base_image.height,
(Math.abs(storeRects[0].w)/canvas.width) * pre_base_image.width ,
(Math.abs(storeRects[0].h)/canvas.height) * pre_base_image.height,
0, 0,
Math.abs(storeRects[0].w),
Math.abs(storeRects[0].h)
);
isMoving = false;
}
}
<canvas id="myCanvas" width="800" height="500" style="border:1px solid #000000;">
</canvas>
<canvas id="myCanvasPreview" width="800" height="500" style="border:1px solid #d3d3d3;">
</canvas>
當我選擇圖像中的人,我想預覽它在其他畫布。 現在,我可以預覽,但似乎該地區是不正確的。
您對X和Y點的計算似乎是錯誤的 –
我注意到的另一件事是:您加載600x400的圖像,將其渲染爲800x600的畫布,然後嘗試將該畫布的選擇座標映射到600x400的圖像上加載繪製第二個畫布。那當然會關閉。當我將所有事情稱爲正確的維度時在本地工作。儘管Blindman67的反應很好地解決了這個問題。 – Zomry