Skip to content

Instantly share code, notes, and snippets.

@nabeen
Created November 13, 2019 17:00
Show Gist options
  • Save nabeen/3b21a78aa96dbb98c8ba72f793e00007 to your computer and use it in GitHub Desktop.
Save nabeen/3b21a78aa96dbb98c8ba72f793e00007 to your computer and use it in GitHub Desktop.
toDataURL with Cross Origin image
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<canvas id="canvas"></canvas>
<div id="result"></div>
<?php
$img_base64 = "data:image/jpeg;base64," . base64_encode(file_get_contents('https://www.nabeen.be/authors/admin/avatar_hu98e5db809a8a89fe276a87e5cfbe8704_121675_250x250_fill_q90_lanczos_center.jpg'));
?>
</body>
<script>
const canvas = document.getElementById('canvas');
const canvasWidth = 400;
const canvasHeight = 300;
// Canvasの準備
canvas.width = canvasWidth;
canvas.height = canvasHeight;
const ctx = canvas.getContext('2d');
// Canvas上に画像を表示
const img = new Image();
img.src = <?php echo "'" . $img_base64 . "'"; ?>;
img.onload = function() {
ctx.drawImage(
img,
0,
0,
canvasWidth,
this.height * (canvasWidth / this.width)
);
const data = canvas.toDataURL();
const dlLink = document.createElement('a');
dlLink.href = data;
dlLink.download = 'download.png';
dlLink.innerText = 'DOWNLOAD';
document.getElementById('result').appendChild(dlLink);
};
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment