Преобразование визуализированного содержимого
Используйте преобразование холста для масштабирования визуализированного содержимого.
В приведенном ниже примере используется ctx.translate для размещения визуализации и ctx.scale
для масштабирования.
Преобразование сбрасывается с помощью ctx.setTransform(1, 0, 0, 1, 0, 0)
, что намного быстрее, чем использование ctx.save
и ctx.restore
Масштабировать траекторию, а не обводку
Чтобы lineWidth
оставалось постоянным, преобразование сбрасывается после определения траектории Безье и до stroke
Вызывается .
requestAnimationFrame(mainLoop); // start animation
const ctx = canvas.getContext("2d");
const heart = {
x: 100, y : 100, scale : 1,
draw() {
ctx.fillStyle = "Red";
ctx.lineWidth = 4;
ctx.translate(this.x, this.y); // set origin
ctx.scale(this.scale, this.scale); // set scale
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.bezierCurveTo(82, -40, 0, -80, 0, -50);
ctx.bezierCurveTo(0, -80, -80, -40, 0, 0);
// to keep the line width constant reset the transform after defining the path
ctx.setTransform(1, 0, 0, 1, 0, 0); // restore default transform
ctx.stroke();
ctx.fill();
}
}
function mainLoop(time) {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
heart.scale = Math.sin(time / 100) * 0.2 + 1; // animate scale
heart.draw();
requestAnimationFrame(mainLoop);
}
<canvas id="canvas"></canvas>