Dan*_*J F 2 javascript canvas html5-canvas
假设我们正在画布上动态绘制分形。由于我们不知道分形有多大,因此在某些时候我们需要缩放(缩小)画布以适应分形。
我们该怎么做呢?如何缩放:
return x
,不是return x * scale
,如果可能的话)请参阅下面的小示例。
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)
您可以通过画布变换缩放、平移和旋转绘图坐标。
如果您有绘图的最小和最大坐标
例子:
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)
如果您一开始不知道绘图区域的大小,那么您将需要随时保存绘图坐标。当最小值和最大值发生变化时,您将重新计算变换,清除画布并重新绘制。如果一开始就不知道尺寸,就没有其他办法了。
归档时间: |
|
查看次数: |
1047 次 |
最近记录: |