简体   繁体   English

无法在画布上设置高度和宽度

[英]Not able to set height and width on a canvas

I am creating a canvas object with javascript and trying to set height and width on it, but it isn't creating a canvas with the required dimensions.我正在使用 javascript 创建一个画布对象并尝试在其上设置高度和宽度,但它没有创建具有所需尺寸的画布。 Please tell me where I am going wrong.请告诉我哪里出错了。 Here's the code -这是代码 -

const canvas = document.createElement('canvas');
const a = document.createElement('a');
canvas.style.height = '1000px';
canvas.style.width = '1000px';
a.href = canvas.toDataUrl('image/jpg');
a.download = 'download.jpg';
a.click();

The downloaded image seems to be of much smaller dimensions and not of what is specified(1000px * 1000px)下载的图像似乎尺寸小得多,而不是指定的尺寸(1000px * 1000px)

If you want to set the width/height of a HTMLCanvasElement, you need to set them directly on the canvas element, not on its style.如果要设置 HTMLCanvasElement 的宽度/高度,则需要直接在 canvas 元素上设置它们,而不是在其样式上设置。 So it should look like this:所以它应该是这样的:

const canvas = document.createElement('canvas');
const a = document.createElement('a');
canvas.height = '1000px';
canvas.width = '1000px';
a.href = canvas.toDataURL('image/jpg');
a.download = 'download.jpg';
a.click();

Also, you misspelled the function .toDataURL() , URL is capitalized there.此外,您拼错了函数.toDataURL() ,URL 在那里大写。

Try with attributes, not the style: canvas.height instead of canvas.style.height .尝试使用属性,而不是样式: canvas.height而不是canvas.style.height One is the presented resolution, the other is the actual pixel height.一个是呈现的分辨率,另一个是实际像素高度。 It's confusing, but let's you control upscaling.这令人困惑,但让您控制升级。

<canvas id="canvas" width="1000" height="1000"></canvas>

Should give you a canvas with a 1000x1000 resolution.应该给你一个 1000x1000 分辨率的画布。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM