html canvas blob image 污染源
Posted qianbo_insist
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html canvas blob image 污染源相关的知识,希望对你有一定的参考价值。
html canvas 被污染
当html中的图片来自于另外一个网站时,canvas被污染,这样,toDataURL和toBlob等函数等都不可以输出了,当canvas被污染的时候怎么做?https://developer.mozilla.org/的解决方案如下图:
canvas 其中的图片来自于另外一个网站,再在四周画一个框,然后输出,正常。
show me the code
代码如下,和官方解决方式不太一样,我们使用下载图片,得到二进制来做这个事情。一样达到效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas toBlob and download</title>
</head>
<body>
<!-- <img src ="http://192.168.0.129:8089/0.png" /> -->
<canvas id="canvas"></canvas>
</body>
<script>
function downloadByBlob(blobObj) {
const link = document.createElement('a');
link.style.display = 'none';
const downloadUrl = window.URL.createObjectURL(blobObj);
link.href = downloadUrl;
link.download = `test.png`;
document.body.appendChild(link);
link.click();
link.remove();
};
function getImageBlob(ctx,url,callback) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = function () {
if (parseInt(this.status, 10) === 200) {
if (typeof callback === 'function') {
callback(ctx,URL.createObjectURL(this.response));
}
}
};
xhr.send();
}
function getImage(ctx, e) {
const img = new Image();
img.src = e;
img.onload = function () {
ctx.rect(0,0,640,360);
ctx.lineWidth = 10;
ctx.strokeStyle = "red";
ctx.stroke();
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, 400, 400);
canvas.toBlob(
function (blob) {
url = URL.createObjectURL(blob);
downloadByBlob(blob);
});
}
}
var canvas = document.getElementById("canvas");
canvas.width = 640;
canvas.height = 360;
var context = canvas.getContext('2d');
getImageBlob(context,'http://192.168.0.129:8089/0.png',
getImage);
// getImageBlob(context,'http://192.168.0.240:3002/cache/convert/97e2e43c222f86e4e4293f2b6996a51f/0.png',
// getImage);
// var dImg = document.createElement("img");
// //dImg.crossOrigin = "*";
// dImg.src = "http://192.168.0.240:3002/cache/convert/97e2e43c222f86e4e4293f2b6996a51f/0.png"
// dImg.onload = function(){
// //URL.revokeObjectURL(url);
// dImg.setAttribute("crossOrigin",'Anonymous')
// console.log("draw over");
// context.rect(0,0,640,360);
// context.moveTo(10,10);
// context.lineTo(100,100);
// context.lineTo(500,100);
// context.lineWidth = 10;
// context.strokeStyle = "red";
// context.stroke();
// context.drawImage(dImg,0,0,200,400);
// canvas.toBlob(
// function (blob) {
// var newImg = document.createElement("img"),
// url = URL.createObjectURL(blob);
// downloadByBlob(blob);
// newImg.onload = function () {
// URL.revokeObjectURL(url);
// };
// newImg.src = url;
// document.body.appendChild(newImg);
// });
</script>
</html>
以上是关于html canvas blob image 污染源的主要内容,如果未能解决你的问题,请参考以下文章
Blob/DataURL/canvas/image的相互转换