gpt4 book ai didi

javascript - 正确的 Canvas 高度和宽度未传递给函数

转载 作者:太空宇宙 更新时间:2023-11-04 04:15:31 25 4
gpt4 key购买 nike

Canvas 元素没有以正确的高度和宽度传递给函数,现在我通过在将 Canvas 传递给接受函数后再次分配 Canvas 的高度和宽度来解决这个问题。由于我是新手,所以我想知道这是否是 Canvas 的问题?

$(document).ready(function(){

calling_function = function(eventObj){
//some code
ajaxOptsFtn = {
url: '/xyz_data/',
dataType: 'json',
data: form_vals,
success: function(resp){
//initialisation for function.
if(resp.var_ready === true){
//dynamically adding canvas element.
var canvas_obj = $('<canvas/>').css({width:160, height:240});
$(clicked_element).children('canvas').remove();
$(clicked_element).append(canvas_obj);
//intilise other arguments with some values
var x = 30;
var y= http://abcs.com/dds.jpg;
var z = resp.apparel_img_url;
var nl = gamma_value;
var wD = 23;
var wU = 26;

acceptingFunction(canvas_obj[0],y,z,x,n,wU,wD);
}
else{
console.log('some other message');
}
},
};
if (data.var_ready) {
$.ajax(ajaxOptsFtn);
}
else{
console.log('some message');
};
};

acceptingFunction = function(canvas_obj,y,z,x,n,wU,wD){

canvas = canvas_obj;
console.log("canvas passed height and width:"+ canvas.height +","+canvas.width);
console.log("re assigning expected values");
canvas.width = 160;
canvas.height = 240;
var context = canvas.getContext('2d');
//some code
AimageObj.onload = function () {
//some code
};

BimageObj.onload = function () {
//some code
};
};

最佳答案

您必须使用其属性而非 CSS 来设置 Canvas 的大小 - 例如:

var canvas_obj = $('<canvas/>').attr({'width': 160, 'height': 240});

如果您不这样做,canvas 元素将默认为 300 x 150 像素大小,该大小仅由 CSS 拉伸(stretch)(如图像)。

同样,当您想要获取 Canvas 的大小时,您也会读取相同的属性。

我有written a blog post that explains this in details - 这对 SO 来说太长了,但这是最重要的部分:

If we don’t set any actual size for the canvas’ source bitmap it will default to 300 x 150 pixels as per specification. If you now set the CSS size of the element to lets say 900 x 450 pixels what happens is that those 300 x 150 pixels are simply scaled to the new size as the CSS applies to the element while the default 300 x 150 applies to the source bitmap (ie. the image). The applied CSS rule doesn’t do anything with the actual bitmap size.

It would be exactly the same if the canvas was an image, which works in a similar fashion: it has the image element and then the source bitmap – the image itself. If you choose to use a different size for the element than what the image is, the image is simply stretched but its original data stays the same. There are no more or less pixels in the original image.

关于javascript - 正确的 Canvas 高度和宽度未传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20015641/

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