我正在尝试在 Canvas 中使用 cover
模拟来显示图像。我找到了一些很酷的 answer关于如何去做。
到目前为止,我的图像会根据屏幕分辨率发生变化,但只有在刷新页面后才会发生变化。
我怎样才能得到以下 scaling effect不刷新页面? 尝试调整那里的窗口大小。
HTML
<canvas id="canvas"></canvas>
JS
var ctx = canvas.getContext('2d'),
img = new Image;
canvas.setAttribute('width', window.innerWidth);
canvas.setAttribute('height', window.innerHeight);
img.onload = draw;
img.src = 'https://upload.wikimedia.org/wikipedia/commons/0/0f/2010-02-19_3000x2000_chicago_skyline.jpg';
function draw() {
drawImageProp(ctx, this, 0, 0, canvas.width, canvas.height);
}
/**
* By Ken Fyrstenberg
*
* drawImageProp(context, image [, x, y, width, height [,offsetX, offsetY]])
*
* If image and context are only arguments rectangle will equal canvas
*/
function drawImageProp(ctx, img, x, y, w, h, offsetX, offsetY) {
if (arguments.length === 2) {
x = y = 0;
w = ctx.canvas.width;
h = ctx.canvas.height;
}
/// default offset is center
offsetX = offsetX ? offsetX : 0.5;
offsetY = offsetY ? offsetY : 0.5;
/// keep bounds [0.0, 1.0]
if (offsetX < 0) offsetX = 0;
if (offsetY < 0) offsetY = 0;
if (offsetX > 1) offsetX = 1;
if (offsetY > 1) offsetY = 1;
var iw = img.width,
ih = img.height,
r = Math.min(w / iw, h / ih),
nw = iw * r, /// new prop. width
nh = ih * r, /// new prop. height
cx, cy, cw, ch, ar = 1;
/// decide which gap to fill
if (nw < w) ar = w / nw;
if (nh < h) ar = h / nh;
nw *= ar;
nh *= ar;
/// calc source rectangle
cw = iw / (nw / w);
ch = ih / (nh / h);
cx = (iw - cw) * offsetX;
cy = (ih - ch) * offsetY;
/// make sure source rectangle is valid
if (cx < 0) cx = 0;
if (cy < 0) cy = 0;
if (cw > iw) cw = iw;
if (ch > ih) ch = ih;
/// fill image in dest. rectangle
ctx.drawImage(img, cx, cy, cw, ch, x, y, w, h);
}
最佳答案
在 window resize event 上添加对 draw
的调用:
window.onresize = draw;
这应该可以解决问题。
代替:
drawImageProp(ctx, this, 0, 0, canvas.width, canvas.height);
在draw
函数中传递img
:
drawImageProp(ctx, img, 0, 0, canvas.width, canvas.height);
然后,将宽度/高度设置移动到draw
函数中,导致:
function draw() {
canvas.setAttribute('width', window.innerWidth);
canvas.setAttribute('height', window.innerHeight);
drawImageProp(ctx, img, 0, 0, canvas.width, canvas.height);
}
您可能还想对重绘进行去抖动处理:
var timeOut;
window.onresize = function(){
if(timeOut)
clearTimeout(timeOut);
timeOut = setTimeout(draw, 10);
}
这可以防止 draw
函数在调整窗口大小时每秒被调用几次。
这是 a working example ,从您的 codepen 派生。
关于javascript - 如何在 Canvas 中缩放图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33368723/