В следующем коде я хочу добавить текст, который скрыт точками после нажатия кнопки «Создать изображение для слепых». Теперь мой следующий код дает мне точечное изображение, но моя проблема в том, что я хочу, чтобы изображение было 600600 пикселей, но оно дает мне 539539 изображений после загрузки, нажав кнопку «Загрузить». Кроме того, точки не полностью отображаются на всем загруженном изображении.
Кнопка загрузки не работает в Stackoverflow, но работает правильно в JsFiddle и других ожидаемых платформах: https://jsfiddle.net/0y13Lpan/
Мой загруженный образ таков:
539539 (какой хочу 600600) размер и точки не полностью видны на всем изображении.
Код:
var dotRatio = 20; // Default dot ratio, you can change this value as desired
function generateColorBlindImage() {
// Get the container div element
var containerElement = document.getElementById('container');
// Reduce the opacity of the text
document.getElementById('text').style.opacity = 0.2; /* Set the opacity to 20% */
// Show the dotted pattern
document.querySelector('.dotted').style.display = 'block';
// Generate the color blind image (same as previous code)
// ...
}
function downloadImage() {
// Get the container div element
var containerElement = document.getElementById('container');
// Show the dotted pattern before capturing the image
document.querySelector('.dotted').style.display = 'block';
// Convert the container div to a canvas
html2canvas(containerElement, {width: 600, height: 600}).then(function(canvas) {
// Draw the dotted pattern on the canvas with the specified dot ratio
var ctx = canvas.getContext('2d');
var patternSize = dotRatio;
for (var x = 0; x < canvas.width; x += patternSize) {
for (var y = 0; y < canvas.height; y += patternSize) {
ctx.fillStyle = 'black';
ctx.beginPath();
ctx.arc(x, y, 2, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
}
}
// Create a temporary link element
var link = document.createElement('a');
link.href = canvas.toDataURL();
link.download = 'color_blind_image.png';
// Append the link to the body and click it to trigger download
document.body.appendChild(link);
link.click();
// Remove the link from the body after download
document.body.removeChild(link);
// Reset the container size and hide the dotted pattern after download
containerElement.style.width = '';
containerElement.style.height = '';
document.querySelector('.dotted').style.display = 'none';
}, 500); // Wait for 500 milliseconds (0.5 seconds) before capturing the image
} #container {
position: relative;
width: 600px;
height: 600px;
background-color: lightgray;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
}
/* Style for the text */
#text {
font-size: 48px;
font-family: Arial, sans-serif;
color: red;
opacity: 0.5; /* Set the opacity to 50% */
}
/* Style for the dotted pattern */
.dotted {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none; /* Hide the dotted pattern by default */
}<html>
<head>
<script src = "https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
</head>
<body>
<div id = "container">
<!-- Text to be displayed -->
<div id = "text">LOVE</div>
<!-- Dotted pattern to surround the text -->
<div class = "dotted"></div>
</div>
<!-- Button to generate color blind image -->
<button onclick = "generateColorBlindImage()">Generate Color Blind Image</button>
<!-- Button to download the generated image -->
<button onclick = "downloadImage()">Download Image</button>
</body>
</html>


![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


1. Холст не подходящего размера
После просмотра документа html2canvas я думаю, что основная причина заключается в следующем: «масштаб: масштаб, используемый для рендеринга. По умолчанию используется соотношение пикселей устройства браузера». Для меня каким-то образом мой браузер по умолчанию использует шкалу 1,5.
Я взял ссылку из этого выпуска github.
Адаптация из опубликованных ответов, изменение
html2canvas(containerElement, {width: 600, height: 600}).then(function(canvas)
к
html2canvas(containerElement, {scale: 1}).then(function(canvas)
решает проблему масштабирования, поскольку фиксирует масштаб на 1.
2. Точки не заполняют холст
Далее, для проблемы с точками, не заполняющими весь холст,
for (var x = 0; x < canvas.width; x += patternSize) {
for (var y = 0; y < canvas.height; y += patternSize)
это проблема неравенства < не рисование последней строки/столбца точек, поэтому я изменил код выше на код ниже:
for (var x = 0; x <= canvas.width; x += patternSize) {
for (var y = 0; y <= canvas.height; y += patternSize) {
Я обновил скрипку здесь: https://jsfiddle.net/n80r6ujc/
Я скачал образ по вашей ссылке (jsfiddle.net/0y13Lpan). Размер изображения 600 х 600 пикселей. Может быть... в вашем проекте какие-то неправильные настройки css?