Похожие чаты

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 ответов

11 просмотров

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...

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

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

Карта сайта