【发布时间】:2020-01-07 18:39:05
【问题描述】:
我正在尝试编写一个函数,该函数采用 x,y 坐标和旋转,并将围绕图像中心点旋转的图像插入到画布中。此代码工作正常:
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">
但是当我尝试调整画布大小时
canvas.width =window.innerWidth;
canvas.height = window.innerHeight;
这会扭曲图像并改变旋转点,在更大的窗口上效果更清晰。我怎样才能拥有一个填满屏幕的画布并将其视为我使用 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">
【问题讨论】:
标签: javascript canvas