Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript HTML画布Img缩放不知何故不起作用_Javascript_Html_Image_Canvas_Resize - Fatal编程技术网

Javascript HTML画布Img缩放不知何故不起作用

Javascript HTML画布Img缩放不知何故不起作用,javascript,html,image,canvas,resize,Javascript,Html,Image,Canvas,Resize,我正在尝试通过Javascript缩放本地图像,如下所示: function resizeImage(file, func){ var canvas = document.createElement('canvas'); var img = new Image(); img.onload = function () { var factor = img.width/800; canvas.width = 800; canva

我正在尝试通过Javascript缩放本地图像,如下所示:

function resizeImage(file, func){
    var canvas = document.createElement('canvas');
    var img = new Image();
    img.onload = function () {
        var factor = img.width/800;
        canvas.width = 800;
        canvas.height = img.height/factor;
        ctx = canvas.getContext('2d');
        ctx.scale(factor, factor);
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        func(canvas.toDataURL());
    }
    img.src = file.dataload; //file is an json-Object and dataload a dataURI
}
不知何故,canvas.toDataURL()返回的数据不会以任何方式调整大小。 我仔细检查了canvas.width和canvas.height是否是正确的计算尺寸


知道哪里出了问题吗?

尝试删除
scale()
方法,因为它只会影响绘制到画布位图的内容,而不会影响位图本身(无论如何,
drawImage()
都会正确缩放图像)

您需要使用
宽度
高度
属性缩放画布。这些是使用
toDataURL()
获得维度的基础

如果您需要canvas元素在屏幕上保持不变,也可以对其应用CSS:

canvas.style.width = 800 + 'px'; 
canvas.style.height = img.height/factor + 'px';
canvas.style.width = 800 + 'px'; 
canvas.style.height = img.height/factor + 'px';