【问题标题】:How to transfer rectangle coordinates from one canvas to another in Html5?如何在 Html5 中将矩形坐标从一个画布转移到另一个画布?
【发布时间】:2020-05-17 11:51:20
【问题描述】:

我正在使用一些代码来动态地将画布上矩形的坐标转移到另一个画布,以便在canvas2上的确切位置绘制矩形。 p>

我在 stackoverflow 上遇到过不同的类似问题和解决方案,例如:link1link2,但它们都不适用于我的情况。

sendimg() 函数将矩形坐标从 canvas1 传输到 canvas2。由于 canvas2 图像被缩放到大尺寸,矩形没有绘制在正确的位置。

详情请查看随附的 sn-p 或codepen link

var canvas = document.getElementById("canvas1");
var canvas2 = document.getElementById("canvas2");

var ctx = canvas.getContext("2d");
var ctx2 = canvas2.getContext("2d");

var img = new Image();
var rect = {};
var scale = 0;
var scale2 = 0;
var x = 0;
var y = 0;
var x2 = 0;
var y2 = 0;
var drag = false;


img.onload = function () {
	//Setting dpi for canvas1
	var dpi = window.devicePixelRatio || 1;
	canvas.setAttribute('width', canvas.clientWidth * dpi);
	canvas.setAttribute('height', canvas.clientHeight * dpi);
	
	//Setting dpi for canvas2
	var dpi = window.devicePixelRatio || 1;
	canvas2.setAttribute('width', canvas2.clientWidth * dpi);
	canvas2.setAttribute('height', canvas2.clientHeight * dpi);
				
	
	ctx.clearRect(0, 0, canvas.clientWidth, canvas.clientHeight);
	ctx.save();
	
	ctx2.clearRect(0, 0, canvas.clientWidth, canvas.clientHeight);
	ctx2.save();
	
	//fitting image to canvas fill
	scale = Math.max(canvas.clientWidth / img.width, canvas.clientHeight / img.height); //canvas1 scale
	scale2 = Math.max(canvas2.clientWidth / img.width, canvas2.clientHeight / img.height); //canvas2 scale

    x = (canvas.clientWidth / 2) - (img.width / 2) * scale; //canvas1 x
    y = (canvas.clientHeight / 2) - (img.height / 2) * scale; //canvas1 y

	x2 = (canvas2.clientWidth / 2) - (img.width / 2) * scale2; //canvas2 x
    y2 = (canvas2.clientHeight / 2) - (img.height / 2) * scale2; //canvas2 y
	
    ctx.drawImage(img, x, y, img.width * scale, img.height * scale);
	ctx2.drawImage(img, x2, y2, img.width * scale2, img.height * scale2);
	
    canvas.addEventListener('mousedown', mouseDown, false);
    canvas.addEventListener('mouseup', mouseUp, false);
    canvas.addEventListener('mousemove', mouseMove, false);

}
img.crossOrigin = "Anonymous";
img.src = 'https://i.imgur.com/1n8sbrF.jpg';

function mouseDown(e) {
    rect.startX = e.clientX - this.offsetLeft;
    rect.startY = e.clientY - this.offsetTop;
    drag = true;
}

function mouseUp() { 
	drag = false; 
	console.log(rect);
}

function mouseMove(e) {
    if (drag) {
        ctx.clearRect(0, 0, canvas.clientWidth, canvas.clientHeight);
        ctx.save();
        ctx.drawImage(img, x, y, img.width * scale, img.height * scale);
        rect.w = (e.clientX - this.offsetLeft) - rect.startX;
        rect.h = (e.clientY - this.offsetTop) - rect.startY;
		ctx.lineWidth  = 2;
        ctx.strokeStyle = 'red';
        ctx.strokeRect(rect.startX, rect.startY, rect.w, rect.h);
    }
}

function sendimg()
{
	if(rect.startX === undefined)
	{
		alert("draw any rectangle first on canvas1");
		return false;
	}
	ctx2.lineWidth = 2;
	ctx2.strokeStyle = "yellow";
	//Following code is not drawing rectangle on correct position
	ctx2.strokeRect(rect.startX * scale2 + x2 , rect.startY* scale2 + y2, rect.w * scale2 , rect.h * scale2);
  
}
html, body{
  width: 90%;
  height: 90%;
  }
#div1 {
  margin: 10px;
  width: 800px;
  height: 600px;
  border: 2px solid red;
}

#div2 {
  position: absolute;
  top: 20px;
  left: 900px;
  margin: 10px;
  width: 1200px;
  height: 800px;
  border: 2px solid red;
}

canvas {
  width: 100%;
  height: 100%;
}
<button type="button" onclick="sendimg();">Send Rectangle on Canvas2</button>
<div id="div1">
	<canvas id="canvas1"></canvas>
</div>

<div id="div2">
	<canvas id="canvas2"></canvas>
</div>

【问题讨论】:

  • 我没有完全调试你的代码,但问题肯定来自你定义X坐标的地方。由于 canvas.width ctx2.strokeRect(rect.startX * scale2 - x2 中的符号更改为减号来查看它(或者添加 x2 的绝对值)。 Is 没有在完全正确的位置绘制新矩形,所以我猜还有别的东西。
  • 感谢@Serge P 尝试并指出线索。

标签: javascript jquery html5-canvas


【解决方案1】:

一些主要和次要问题

  • 重要提示 当您调用 ctx.save 时,您会将当前 2D 画布状态推送到堆栈。如果您不致电ctx.restore,则致电ctx.save 毫无意义。更糟糕的是,每次调用 save 都会占用内存。
  • window 是全局 this。你不需要使用它。例如window.devicePixelRatiodevicePixelRatio 相同
  • 您不需要使用setAttribute。仅当您希望标记反映属性状态并且该属性不是由 DOM 定义时,才使用 setAttribute
  • 当您设置画布widthheight 时,画布被清除并且状态被重置为默认值。设置大小后无需清除画布,也无需保存状态。
  • 简化数学。当你计算原点时,你有类似(a / 2) - (b / 2) * c 的东西。它有一个公约数2,因此变成(a - b) * c / 2

坐标系

使用通用坐标系并在渲染到任一画布时进行转换。由于两个画布都渲染相同的图像(并且它接缝的是相关坐标系的图像)使用图像坐标系。

您有 4 个坐标系,图像、缩放图像 canvas1、缩放图像 canvas2 和 rect 作为 canvas1 像素。问题是您正在从 canvas1 像素坐标 (rect) 转换为 canvas2 图像坐标

要修复缩放和定位,请将 canvas1 像素坐标转换为图像坐标(参见示例函数 mouseEvents)。然后在您的渲染函数中将图像坐标转换回画布像素坐标(参见示例函数updateCanvas)。

示例

我删除了很多不需要和重复的代码,以降低复杂性并使代码更具可读性和可维护性。使用现代 JS 并添加了一些 UI

  • 设置画布的单个函数
  • 处理鼠标事件的单个函数
  • 渲染矩形的单个函数
  • 使用光标“十字准线”和“无”提供反馈

对于示例,我删除了按钮(与问题无关),减小了两个画布大小以适应非常小的 sn-p 窗口,并在绘制第一个矩形时实时更新第二个矩形。

请注意,rect 位于图像坐标中。

const COLOR1 = "#F00", COLOR2 = "#FF0", LINE_WIDTH = 2;
const ctx1 = canvas1.getContext("2d"), ctx2 = canvas2.getContext("2d");
const img = new Image;
const rect = {};
var drag = false;

img.src = "https://i.imgur.com/1n8sbrF.jpg";
img.addEventListener("load",() => {
    setupCanvas(ctx1);
    setupCanvas(ctx2);
    canvas1.addEventListener("mousedown", mouseEvent);
    canvas1.addEventListener("mouseup", mouseEvent);
    canvas1.addEventListener("mousemove", mouseEvent);
}, {once: true});

function setupCanvas(ctx, coords = {}) {
    const dPR = devicePixelRatio || 1;
    const w = ctx.canvas.width  = ctx.canvas.clientWidth * dPR;
    const h = ctx.canvas.height = ctx.canvas.clientHeight * dPR;
    const scale = coords.scale = Math.max(w / img.width, h / img.height);
    const x = coords.x = (w - img.width * scale) / 2;
    const y = coords.y = (h - img.height * scale) / 2;
    ctx.drawImage(img, x, y, img.width * scale, img.height * scale);
    ctx.canvas.coords = coords;
}
function mouseEvent(e) {
    var cursor = "crosshair";
    const co = canvas1.coords;
    const x = (e.clientX - this.offsetLeft - co.x) / co.scale;  
    const y = (e.clientY - this.offsetTop - co.y) / co.scale;
    if (e.type === "mousedown") {
        rect.x = x;
        rect.y = y;
        drag = true;
        canvas1.title = "";
    } else if (e.type === "mouseup") { drag = false }
    if (drag) {
        cursor = "none";
        rect.w = x - rect.x;
        rect.h = y - rect.y;
        updateCanvas(ctx1, COLOR1, co);
        updateCanvas(ctx2, COLOR2, canvas2.coords);
    }
    canvas1.style.cursor = cursor;
}

function updateCanvas(ctx, color, {x, y, scale}) {
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    ctx.drawImage(img, x, y, img.width * scale, img.height * scale);
    ctx.lineWidth = LINE_WIDTH;
    ctx.strokeStyle = color;
    ctx.strokeRect(x + rect.x * scale, y + rect.y * scale, rect.w * scale, rect.h * scale);
}
html, body{
  width: 90%;
  height: 90%;
  }
#div1 {
  margin: 10px;
  width: 200px;
  height: 300px;
  border: 2px solid red;
}

#div2 {
  position: absolute;
  top: 10px;
  left: 240px;
  width: 300px;
  height: 200px;
  border: 2px solid #FF0;
}

canvas {
  width: 100%;
  height: 100%;
}
<div id="div1">
	<canvas id="canvas1" title="Click and drag to select area."></canvas>
</div>

<div id="div2">
	<canvas id="canvas2"></canvas>
</div>

【讨论】:

  • 感谢您纠正和减少大量代码。你是对的,我需要获取图像的矩形坐标(来自缩放的 canvas1)并将其传输到 image2(这将是实际大小)。最终像魅力一样工作。
  • @JackPaul 图像被缩放以填充(与您的问题相同的方法)左右画布。 rect 中的坐标始终位于由 img.widthimg,height 定义的图像像素坐标中,这发生在 mouseEvents 的前 3 行中。在您的问题中,rectxy(在图像坐标中)是在鼠标按下时设置的。
  • 您好@Blindman67,为什么代码在单独创建的html文件上运行良好,但在从附加的sn-p运行时没有从确切的鼠标按下点创建矩形?也请检查此codepen link。我已将 ctx.drawImage(img, x, y, img.width * scale, img.height * scale); 更改为 ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, w, h); 以使图像适合画布。矩形没有正确绘制。
【解决方案2】:

在应用第二个画布的变换和缩放因子之前,您需要反转第一个画布的缩放和平移。这就像那里的 90%,Y 轴是正确的,但 X 轴是错误的。请参阅我对ctx2.strokeRect 的电话以及它如何反转缩放和平移。我的代码可能被劫持了,因为画布原点位于左上角,而平移和缩放公式假定它位于左下角。

编辑:修正了代码 - 现在应该是正确的。

var canvas = document.getElementById("canvas1");
var canvas2 = document.getElementById("canvas2");

var ctx = canvas.getContext("2d");
var ctx2 = canvas2.getContext("2d");

var img = new Image();
var rect = {};
var scale = 0;
var scale2 = 0;
var x = 0;
var y = 0;
var x2 = 0;
var y2 = 0;
var drag = false;


img.onload = function () {
	//Setting dpi for canvas1
	var dpi = window.devicePixelRatio || 1;
	canvas.setAttribute('width', canvas.clientWidth * dpi);
	canvas.setAttribute('height', canvas.clientHeight * dpi);
	
	//Setting dpi for canvas2
	var dpi = window.devicePixelRatio || 1;
	canvas2.setAttribute('width', canvas2.clientWidth * dpi);
	canvas2.setAttribute('height', canvas2.clientHeight * dpi);
				
	
	ctx.clearRect(0, 0, canvas.clientWidth, canvas.clientHeight);
	ctx.save();
	
	ctx2.clearRect(0, 0, canvas.clientWidth, canvas.clientHeight);
	ctx2.save();
	
	//fitting image to canvas fill
	scale = Math.max(canvas.clientWidth / img.width, canvas.clientHeight / img.height); //canvas1 scale
	scale2 = Math.max(canvas2.clientWidth / img.width, canvas2.clientHeight / img.height); //canvas2 scale

    x = (canvas.clientWidth / 2) - (img.width / 2) * scale; //canvas1 x
    y = (canvas.clientHeight / 2) - (img.height / 2) * scale; //canvas1 y

	x2 = (canvas2.clientWidth / 2) - (img.width / 2) * scale2; //canvas2 x
    y2 = (canvas2.clientHeight / 2) - (img.height / 2) * scale2; //canvas2 y
	
    ctx.drawImage(img, x, y, img.width * scale, img.height * scale);
	ctx2.drawImage(img, x2, y2, img.width * scale2, img.height * scale2);
	
    canvas.addEventListener('mousedown', mouseDown, false);
    canvas.addEventListener('mouseup', mouseUp, false);
    canvas.addEventListener('mousemove', mouseMove, false);
    console.log(scale)
    console.log(scale2)
}
img.crossOrigin = "Anonymous";
img.src = 'https://i.imgur.com/1n8sbrF.jpg';

function mouseDown(e) {
    rect.startX = e.clientX - this.offsetLeft;
    rect.startY = e.clientY - this.offsetTop;
    drag = true;
}

function mouseUp() { 
	drag = false; 
	console.log(rect);
}

function mouseMove(e) {
    if (drag) {
        ctx.clearRect(0, 0, canvas.clientWidth, canvas.clientHeight);
        ctx.save();
        ctx.drawImage(img, x, y, img.width * scale, img.height * scale);
        rect.w = (e.clientX - this.offsetLeft) - rect.startX;
        rect.h = (e.clientY - this.offsetTop) - rect.startY;
		ctx.lineWidth  = 2;
        ctx.strokeStyle = 'red';
        ctx.strokeRect(rect.startX, rect.startY, rect.w, rect.h);
    }
}

function sendimg()
{
	if(rect.startX === undefined)
	{
		alert("draw any rectangle first on canvas1");
		return false;
	}
	ctx2.lineWidth = 2;
	ctx2.strokeStyle = "yellow";
	//Following code is not drawing rectangle on correct position
	ctx2.strokeRect( ((rect.startX - x )/scale) * scale2 + x2, 
                   ((rect.startY - y )/scale) * scale2 + y2, 
                   (rect.w/scale) * (scale2), 
                   (rect.h/scale) * (scale2));
  
}
html, body{
  width: 90%;
  height: 90%;
  }
#div1 {
  margin: 10px;
  width: 800px;
  height: 600px;
  border: 2px solid red;
}

#div2 {
  position: absolute;
  top: 20px;
  left: 900px;
  margin: 10px;
  width: 1200px;
  height: 800px;
  border: 2px solid red;
}

canvas {
  width: 100%;
  height: 100%;
}
<button type="button" onclick="sendimg();">Send Rectangle on Canvas2</button>
<div id="div1">
	<canvas id="canvas1"></canvas>
</div>

<div id="div2">
	<canvas id="canvas2"></canvas>
</div>

【讨论】:

  • 谢谢@Jeff,你让它工作得很好。另一个疑问,我只想使用canvas1来绘制矩形,然后将它的绳索传递给python api来处理图像上的这些绳索(在python端处理)。但是这个图像将是它的实际大小(不是 canvas1 的大小)。如果没有 scale2,它将如何工作?目标是图像来自外部 api 在画布上,我需要在其中绘制矩形并将其坐标发送回 api 以进一步处理。如何修改变换和缩放值以适应实际图像大小?
猜你喜欢
  • 2015-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-23
  • 2011-10-15
  • 2015-10-22
  • 2011-06-03
  • 1970-01-01
相关资源
最近更新 更多