本文介绍了在画布上画线-意外的比例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难描述/呈现问题,因为这部分代码深入我的Angular应用程序内部.

I've a hard problem to describe/present, because this part of code is deeply inside my Angular app.

无论如何,我有一个div 350px x 350px,我会用画布覆盖它,并在上面画一条线.

Anyway, I have a div 350px x 350px and I would cover it by canvas, and draw a line on it.

我做了什么?我在表格之前创建了一个canvas标签,并应用了以下CSS规则:

What I did? I created a canvas tag before the table and apply this CSS rules:

canvas{
  position: absolute;
  width: 350px;
  height: 350px;
  border: dotted black 2px; <-- only for visual effect
}

涵盖了div.

接下来,我试图画一条简单的线来对其进行测试(我错过了这里的一部分代码,因为它可以工作,因此下载了对canvas的引用):

Next I tried to draw a simple line to test it (I missed here part of code which download reference to canvas, because it works):

const ctx = canvasNativeEl.getContext('2d');
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100, 100);
ctx.stroke();

我希望得到对角线正方形.不幸的是,我得到了矩形的对角线,像这样:

I expected to get a diagonal of square. Unfortunately I got diagonal of rectangle, like this:

这个问题不允许我画目标线,因为坐标是错误的.

This problem doesn't allow me to draw a target line, because coordinates are wrong.

如果您有任何想法,我很乐意看到.问候!

If You have any ideas I would gladly see it.Regards!

推荐答案

正如我解释的的问题是,在画布上使用width/height属性会产生缩放效果.为了更好地了解您的问题,请在此之前/之后进行

As I explained in a previous question The issue is that using width/height properties on canvas will create a scale effect. Here is a before/after to better see your issue:

canvasNativeEl = document.querySelectorAll('canvas');

let ctx = canvasNativeEl[0].getContext('2d');
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100, 100);
ctx.stroke();

ctx = canvasNativeEl[1].getContext('2d');
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100, 100);
ctx.stroke();
canvas{
  border: dotted black 2px;
}
<canvas></canvas>
<canvas style="width: 350px;height: 350px;"></canvas>

如您所见,第二个画布是第一个画布的缩放版本.就像我们正确地考虑第一条线,然后更改宽度/高度以获得第二条线一样.

As you can see, the second canvas is a scaled version of the first one. It's like we correctly draw our line considering the first one then after that we change width/height to obtain the second one.

为避免这种情况,您应考虑height/width属性具有正确的坐标并避免缩放效果

In order to avoid this you should consider height/width attribute to have correct coordinates and avoid the scaling effect

canvasNativeEl = document.querySelectorAll('canvas');

let ctx = canvasNativeEl[0].getContext('2d');
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100, 100);
ctx.stroke();

ctx = canvasNativeEl[1].getContext('2d');
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100, 100);
ctx.stroke();
canvas{
  border: dotted black 2px;
}
<canvas></canvas>
<canvas width='350' height="350" ></canvas>

这篇关于在画布上画线-意外的比例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 13:29