Похожие чаты

I want to take a snapshot of a web page

and to save it as an image file.
I've found a sample which does it using canvas, on fiddle it's working fine: https://jsfiddle.net/Sjeiti/opsjbrjL/
When I try to implement it on my webserver with the following code:
<head>
<script type="text/javascript" src="canvas.js"></script>
<link rel="stylesheet" type="text/css" href="canvas.css">
</head>
<body>
<canvas width="100" height="100"></canvas>
<div><a href="#" download="image.png">download image</a></div>
</body>
canvas.js:
const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');
const anchor = document.querySelector('a');
const rand = i=>Math.random()*i<<0
const fileName = image${100+rand(100)}.png;

drawOntoCanvas();
anchor.addEventListener('click', onClickAnchor);

function onClickAnchor(e) {
if (window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(canvas.msToBlob(), fileName);
e.preventDefault();
} else {
anchor.setAttribute('download', fileName);
anchor.setAttribute('href', canvas.toDataURL());
}
}
function drawOntoCanvas(){
const size = 100;
context.fillStyle = 'rgba(255,0,0,0.4)';
let i = 10;
while (i--) {
context.fillRect(rand(size),rand(size),rand(size),rand(size));
}
}
it's not working, not even drawing on the canvas nor saving it to a file.
What am I missing there?

5 ответов

7 просмотров

Are you getting an error in the console?

Fab-horn Автор вопроса
Misan
Are you getting an error in the console?

yes, I get an Uncaught TypeError, Cannot read roprties of null (reading 'getContext') at canvas.js:2:24

Fab horn
yes, I get an Uncaught TypeError, Cannot read ropr...

Ok easy fix: load your js after the html has loaded. Put the script at the end of the body.

Fab-horn Автор вопроса

thanks! I get to draw on the canvas, and it's savint it! now got to see if I can put lot of iframes inside the canvas and to be able to save the image...

Похожие вопросы

Обсуждают сегодня

Anyone here suffers from unexplained aural migraines, who would be up for talking for a bit? Doesn't *have* to be aural, but I am not asking about headaches, I mean actual mi...
Martin Rys
55
Привет, нужен совет старших товарищей. Есть глобальная переменная var DefaultDataFolder:string; инициализируем DefaultDataFolder:='a:\_OUT\'; есть примитивная процедур...
Max Otto
11
A couple thoughts from a random internet stranger: 1. If you want this project to gain traction you cannot keep being negative. If I just came here after finding out about Kd...
Eric Wild
46
Agreed. And on a lighter note, I just love the idea of earning $FunToken while having fun. It’s like getting paid to do what we love. Who wouldn’t want that? 😄
SpaceGemz
13
Вопрос. Теоретический. Есть список команд. Команды отправляю в обработку некой функции, по очереди. Разные команды могут давать разные результаты после обработки. В зависимос...
Serjone
7
We heading to 1.1$ 🤔?
CryptoBo$$
35
But is may still valid as a goal ?
oneBlock!³
10
Сonst magicTgHTML = (text, entities) => { let processedText = text; let offsetShift = 0; entities.forEach(entity => { const { offset, length, type, url, ...
Андрей
1
Всем вечера. Подскажите как лучше сделать. делаю на Д10 Например будет база данных на SQLite. в ней будет много таблиц. более 50шт Типа справочник. Содержать ID Name Id p...
Андрей Т 🐎
10
Im quite curious how Stuart Popejoy, Will, Mike and so on. Relate to the institutional entities they wish to assist in onboarding onto web3. It feels like a pivotal conversa...
Aleksander @1Answers
3
Карта сайта