gpt4 book ai didi

javascript - 当窗口大小调整时,如何调整 HTML5 Canvas 图像的大小

转载 作者:行者123 更新时间:2023-11-28 00:45:55 27 4
gpt4 key购买 nike

我正在设计一个 Google Chrome 应用程序,它有一个用于显示图像的 html5 Canvas 。在通过 ctx.drawImage( ...) 显示图像之前,我确保保留图像的宽高比等。调整窗口大小时,我添加了一个事件监听器和一个函数调用来调整 Canvas 和图像的大小,这是相关的代码片段:

var ctx = document.getElementById('canvas').getContext('2d');

window.onload = function() {
ctx.canvas.width = window.innerWidth-10;
ctx.canvas.height = window.innerHeight-30;
window.addEventListener('resize', resizeCanvas);
};

function resizeCanvas(){
var imgData = ctx.getImageData(0,0, ctx.canvas.width, ctx.canvas.height);
ctx.canvas.width = window.innerWidth-10;
ctx.canvas.height = window.innerHeight-85;
ctx.putImageData(imgData, 0, 0); // Put the image data back onto the canvas
}

但是这不起作用。看来 Canvas 正在正确调整大小(因为我在其上添加了边框并且可以看到它调整),但 putImageData 没有更新图像?对于为什么会发生这种情况有什么想法吗?

更新:根据以下建议:我更改了调整大小功能,尝试重新缩放 Canvas - 但现在调整窗口大小后根本不显示图像

function resizeCanvas(){
//var imgData = ctx.getImageData(0,0, ctx.canvas.width, ctx.canvas.height);

ctx.scale(ctx.canvas.width/window.innerWidth,ctx.canvas.height/window.innerHeight);
ctx.canvas.width = window.innerWidth-10;
ctx.canvas.height = window.innerHeight-85;
//ctx.putImageData(imgData, 0, 0); // DO I NEED THIS NOW?
}

谢谢!

最佳答案

我不确定这是否是最优雅的方法,但我现在所做的是完全重绘原始图像,即:

var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image;

window.onload = function() {
ctx.canvas.width = window.innerWidth-10;
ctx.canvas.height = window.innerHeight-30;
window.addEventListener('resize', resizeCanvas);
};

function drawMainStage(img){

var h = img.height;
var w = img.width;
var image_ratio = h/w;
var canvas_ratio = Math.round(ctx.canvas.height/ctx.canvas.width);

if (ctx.canvas.width >= ctx.canvas.height){
// Landscape canvas, scale using height of canvas
if (h > ctx.canvas.height){

// Image larger in at least one dimension compared to the canvas
var width_scaled = Math.round((ctx.canvas.height/h)*w);
var height_scaled = ctx.canvas.height;

if ( w > h ){
if ( width_scaled > ctx.canvas.width ){
height_scaled = Math.round((ctx.canvas.width/w)*h);
width_scaled = ctx.canvas.width;
}
}
var x1 = ctx.canvas.width/2 - width_scaled/2;
var y1 = ctx.canvas.height/2 - height_scaled/2;
ctx.drawImage(img, 0,0, w,h, x1,y1, width_scaled, height_scaled);
}
else
{
// Images smaller than the canvas
var x1 = Math.round(ctx.canvas.width/2 - w/2);
var y1 = Math.round(ctx.canvas.height/2 - h/2);
ctx.drawImage(img, x1,y1);
}
}
// else {
//TBD}

function resizeCanvas(){
ctx.canvas.width = window.innerWidth-10;
ctx.canvas.height = window.innerHeight-85;
drawMainStage(img);
}

关于javascript - 当窗口大小调整时,如何调整 HTML5 Canvas 图像的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27401447/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com