gpt4 book ai didi

javascript - 在 Canvas 上绘制图像 - 比实际大

转载 作者:技术小花猫 更新时间:2023-10-29 12:13:22 25 4
gpt4 key购买 nike

我想在 Canvas 上从 jpg 文件中绘制图像。我的代码:

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

imageObj.onload = function() {
ctx.drawImage(imageObj, 0, 0);
};
imageObj.src = 'img/my_image.jpg';

问题是 Canvas 上的图像比文件中的图像大得多。为什么?如何绘制实际大小的图像?

更新:结果:http://jsfiddle.net/AJK2t/

最佳答案

这是你的问题:

<canvas style="width: 700px; height: 400px;" id="konf"></canvas>

您设置的是 Canvas 的视觉尺寸,而不是像素数。因此,浏览器正在按比例放大 Canvas 像素。

最简单的修复是:

<canvas width="700" height="400" id="konf"></canvas>

widthheight 参数控制 Canvas 中的像素数。如果没有 CSS 样式, Canvas 的默认视觉大小也将是这个大小,导致每个屏幕像素一个 Canvas 像素(假设您没有缩放网络浏览器)。

my answer to a related question 复制/粘贴:

Think about what happens if you have a JPG that is 32x32 (it has exactly 1024 total pixels) but specify via CSS that it should appear as width:800px; height:16px. The same thing applies to HTML Canvas:

  • The width and height attributes of the canvas element itself decide how many pixels you can draw on. If you don't specify the height and width of the canvas element, then per the specs:
    "the width attribute defaults to 300, and the height attribute defaults to 150."

  • The width and height CSS properties control the size that the element displays on screen. If the CSS dimensions are not set, the intrinsic size of the element is used for layout.

If you specify in CSS a different size than the actual dimensions of the canvas it must be stretched and squashed by the browser as necessary for display. You can see an example of this here: http://jsfiddle.net/9bheb/5/

关于javascript - 在 Canvas 上绘制图像 - 比实际大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15793702/

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