我有一个表单,用户可以通过它跟踪流程,并通过视觉效果显示进度。
我尝试使用进度条矩形的图片和标志的图片。我正在画布上绘制它,但是它们看起来很模糊,包括标题为文本。
这些是原始图片,很清楚:
这是我的代码:
<head>
<style>
#myCanvas {
border: 1px solid #d3d3d3;
width: 100%;
height: 100%;
}
#invis {
display: none;
}
</style>
</head>
<img src="~/Temp/images/track.png"/>
<canvas id="myCanvas"></canvas>
<img src="~/Temp/images/flag.png" id="invis" />
<script>
debugger;
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "15px Arial";
let text = "Email Request Process Live Tracking";
ctx.fillStyle = "#0000ff";
ctx.fillText(text,canvas.width/2 - ctx.measureText(text).width/2,20);
let img1 = new Image();
let startX = 40;
let startY = canvas.height - 50;
let width = canvas.width - 80;
let height = 10;
img1.onload = function () {
ctx.drawImage(img1, startX, startY, width, height)
};
img1.src = "/Temp/images/track.png"
var progress = "FH";
var progress1 = "HR";
var progress2 = "IT";
let locations = {
function: {x: startX-20, y: startY},
FH: {x: startX + width/28, y: startY},
HR: { x: startX + 2 * (width / 4.2), y: startY },
IT: { x: startX + 4 * (width / 4.3), y: startY },
processed: {x: startX + 3 * (width/5), y: startY},
actionPerformed: {x: startX + 4 * (width/5), y: startY},
handedoverClosed: {x: startX + width, y: startY}
};
let img = new Image;
img.onload = function () {
let x = locations[progress].x
let y = locations[progress].y
ctx.drawImage(img, locations[progress].x, locations[progress].y - 40, 20, 40)
};
img.src = "/Temp/images/flag.png"
}
</script>
答案 0 :(得分:3)
您的画布需要明确的宽度和高度:
<canvas width="1000" height="1000"></canvas>
否则,画布中将具有默认的可用像素数,但是这些像素将在屏幕的总宽度上拉伸。
要获得<canvas>
的合适的大小,您应该获得getBoundingClientRect()
画布将占据的尺寸,在元素上明确设置它们,然后重新渲染。否则,您仍然会遇到缩放问题。
请考虑以下示例。第一个渲染将使用默认的画布大小进行,并且您将看到Stack Overflow徽标被拉伸,因为它试图显示的是一个300宽度的画布,该画布跨越了大约600像素。
几秒钟后,画布的尺寸被明确设置为元素的实际计算尺寸。因此,画布不再拉伸。
请记住,如果调整了屏幕大小,则需要进行此计算并重新渲染。
const img = new Image();
function main() {
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
console.log(`${canvas.width} | ${canvas.height}`); // Probably 300 | 150
ctx.drawImage(img, 0, 0, 200, 200);
setTimeout(() => {
const {
width,
height
} = canvas.getBoundingClientRect();
canvas.width = width;
canvas.height = height;
console.log(`${canvas.width} | ${canvas.height}`);
ctx.drawImage(img, 0, 0, 200, 200);
}, 3000);
}
img.addEventListener("load", main);
img.src = "https://cdn.sstatic.net/Img/unified/sprites.svg";
canvas {
width: 100%;
}
<canvas id="canvas"></canvas>