画布:使绘图适合画布大小而不改变坐标

Dan*_*J F 2 javascript canvas html5-canvas

假设我们正在画布上动态绘制分形。由于我们不知道分形有多大,因此在某些时候我们需要缩放(缩小)画布以适应分形。

我们该怎么做呢?如何缩放:

  1. 正确,以便它完全符合我们的图纸,并且
  2. 这样坐标保持不变,并且我们的分形计算不需要使用比例值(意思是,return x,不是return x * scale,如果可能的话)
  3. 如果分形向各个方向生长并且我们有负值怎么办?

请参阅下面的小示例。

var $canvas = document.querySelector('canvas'),
    ctx     = $canvas.getContext('2d'),
    lastX   = 0,
    lastY   = 0;

    drawLoop();


function drawLoop() {
    var newX = lastX + 30,
        newY = lastY + 30;

    ctx.beginPath();
    ctx.moveTo(lastX, lastY);
    ctx.lineTo(newX, newY);
    ctx.stroke();

    lastX = newX;
    lastY = newY;

    setTimeout(drawLoop, 1000);
}
Run Code Online (Sandbox Code Playgroud)
<canvas width="100" height="100" style="border: 1px solid #ccc;"></canvas>
Run Code Online (Sandbox Code Playgroud)

Bli*_*n67 5

您可以通过画布变换缩放、平移和旋转绘图坐标。

如果您有绘图的最小和最大坐标

例子:

const min = {x: 100, y: 200};
const max = {x: 10009, y: 10000}; 
Run Code Online (Sandbox Code Playgroud)

您可以按如下方式使其适合画布

const width = canvas.width;
const height = canvas.height;

// get a scale to best fit the canvas
const scale = Math.min(width / (max.x - min.x), height / (max.y - min.y));

// get a origin so that the drawing is centered on the canvas
const top = (height - (max.y - min.y)) / 2;
const left = (width - (max.x - min.x)) / 2;

// set the transform so that you can draw to the canvas
ctx.setTransform(scale, 0, 0, scale, left, top);

// draw something
ctx.strokeRect(min.x, min.y, max.x - min.x, max.y - min.y);
Run Code Online (Sandbox Code Playgroud)

如果您一开始不知道绘图区域的大小,那么您将需要随时保存绘图坐标。当最小值和最大值发生变化时,您将重新计算变换,清除画布并重新绘制。如果一开始就不知道尺寸,就没有其他办法了。