I am trying to create multiple perspective-transformed rectangles in the lower right corner of a canvas by using ctx.transform:
ctx.transform(1, 0, -1, 1, 10, 10)
.
My goal now is to adjust the size of the drawing based on a variable scale=n
, while keeping the position centered. However, when I move the slider, it changes the position of the shapes. How can I prevent this from happening?
let canvas = document.getElementById("canvas")
canvas.width = canvas.height = 200;
$(canvas).appendTo(document.body)
let ctx = canvas.getContext("2d")
let update = function(input) {
let scale = input.value;
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.transform(1, 0, -1, 1, 10, 10)
for (let i = 0; i < 4; i++) {
ctx.fillStyle = (i === 2) ? "#3b2a19" : "#957e67"
let layer = {
x: canvas.width + scale * 7 - i * scale,
y: canvas.height - scale * 5 - i * scale,
width: scale * 3,
height: scale * 1.5
}
ctx.fillRect(layer.x, layer.y, layer.width, layer.height)
ctx.strokeRect(layer.x, layer.y, layer.width, layer.height)
}
ctx.resetTransform();
}
$("input").trigger("input")
#canvas {
border: 2px solid red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas"></canvas>
<input oninput="update(this)" type="range" min="1" max="20" />