Drawing line on canvas - unexpected scale

泄露秘密 提交于 2020-01-06 07:26:10

问题


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

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

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
}

It covered div.

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!


回答1:


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.

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>


来源:https://stackoverflow.com/questions/53608436/drawing-line-on-canvas-unexpected-scale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!