Saya mencoba menulis fungsi yang mengambil koordinat dan rotasi x,y, dan menyisipkan gambar yang diputar di sekitar titik pusat gambar ke dalam kanvas. Kode ini berfungsi dengan baik:
let img = new Image(),
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
step = 0,
drawImage = (ctx, img, x, y, degrees, w = 150, h = 150) => {
ctx.save();
ctx.translate(x+w/4, y+h/4);
ctx.rotate(degrees*Math.PI/180.0);
ctx.translate(-x-w/4, -y-h/4);
ctx.drawImage(img, x, y, w, h);
ctx.restore();
},
animate = () => {
ctx.globalCompositeOperation = 'destination-over';
// clear canvas
ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
drawImage(ctx, img, 0, 0, step)
step++;
window.requestAnimationFrame(animate);
}
img.src = "http://upload.wikimedia.org/wikipedia/commons/d/d2/Svg_example_square.svg";
animate();
* { margin:0; padding:0; } /* to remove the top and left whitespace */
html, body { width:100%; height:100%; } /* just to be sure these are full screen*/
canvas { display:block;} /* To remove the scrollbars */
<canvas id="canvas" width="300" height="300">
Namun ketika saya mencoba mengubah ukuran kanvas
canvas.width =window.innerWidth;
canvas.height = window.innerHeight;
Ini membengkokkan gambar dan juga mengubah titik rotasi, efeknya lebih jelas pada jendela yang lebih besar. Bagaimana saya bisa memiliki kanvas yang memenuhi layar dan memperlakukannya seolah-olah saya mengatur ukurannya dengan properti HTML?
let img = new Image(),
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
step = 0,
drawImage = (ctx, img, x, y, degrees, w = 300, h = 300) => {
ctx.save();
ctx.translate(x+w/4, y+h/4);
ctx.rotate(degrees*Math.PI/180.0);
ctx.translate(-x-w/4, -y-h/4);
ctx.drawImage(img, x, y, w, h);
ctx.restore();
},
animate = () => {
ctx.globalCompositeOperation = 'destination-over';
// clear canvas
ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
drawImage(ctx, img, 0, 0, step)
step++;
window.requestAnimationFrame(animate);
}
img.src = "http://upload.wikimedia.org/wikipedia/commons/d/d2/Svg_example_square.svg";
canvas.width =window.innerWidth;
canvas.height = window.innerHeight;
animate();
* { margin:0; padding:0; } /* to remove the top and left whitespace */
html, body { width:100%; height:100%; } /* just to be sure these are full screen*/
canvas { display:block;} /* To remove the scrollbars */
<canvas id="canvas" width="300" height="300">