gpt4 book ai didi

javascript - 根据 Canvas 上设置的 dpi 设置文本位置和大小

转载 作者:行者123 更新时间:2023-12-03 05:22:16 27 4
gpt4 key购买 nike

嗨,各位有才华的人,

我正在开发一个用于设计名片的工具。我已将 Canvas 的 dpi 增加到 200,这样客户就可以进行设计,而无需处理实际尺寸。

canvas.width = 3.5 inches * 200;  // width would be 700px 
canvas.height = 2 inches * 200; // height would be 400px

我的问题是如何将文本设置为 200 dpi?我所做的是这样的。

var scale_ratio = 200/72;
var pointsize = 14;
var xcord = 20;
var ycord = 20;

this.context.font = pointsize * scale_ratio + 'px' + " Arial";
this.context.fillText("Hello World", xcord, ycord + pointsize * scale_ratio);

我的做法正确吗?谢谢

最佳答案

ctx.setTransform

设置变换,而不是缩放字体和所有渲染调用参数,以便为您缩放所有渲染。

为标准 DPI 设置字体、线宽等(看起来您使用的是 72 DPI)

const nativeDPI = 72; // what ever value you where using
ctx.font = "14px Arial";
ctx.lineWidth = 1;
const textPos = {x : 20, y : 20};
const box = {x : 3, y : 3, w : 246, h: 138};

使用函数 ctx.setTransform(xAxisX, xAxisY, yAxisY, yAxisY, originX, originY) 将比例渲染到正确的 DPI 时前两个值是像素 x 轴的长度和方向,接下来的两个值是 y 轴,最后两个值是原点的绝对 Canvas 像素坐标。

const workingDPI = 200;
var scale = workingDPI / nativeDPI; // get the scale change
ctx.setTransform(scale, 0, 0, scale, 0, 0); // set the new scale

ctx.fillText("blah blah.", textPos.x, textPos.y);
ctx.strokeRect(box.x, box.y, box.w, box.h);

如果您需要恢复到像素比例,您可以设置默认变换

ctx.setTransform(1, 0, 0, 1, 0, 0);

关于javascript - 根据 Canvas 上设置的 dpi 设置文本位置和大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41325819/

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