无法在javascript中将图像绘制到画布
Posted
技术标签:
【中文标题】无法在javascript中将图像绘制到画布【英文标题】:Can't draw image to canvas in javascript 【发布时间】:2022-01-01 03:35:17 【问题描述】:我正在尝试在输入图像上添加水印图像,然后再将其保存到数据库中。我正在使用画布来执行此操作,然后将画布转换回 blob,但是当我引用项目本地文件目录中的水印图像以绘制到画布上时,我得到“可能无法导出受污染的画布”。控制台出错。
// Read input file
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () =>
// Create canvas & calculate Stamp size and position
const canvas = document.createElement("canvas");
canvas.width = canvasSize.width;
canvas.height = canvasSize.height;
var calcW = canvasSize.width/2;
var calcH = calcW/2.16;
var calcX = (canvasSize.width - calcW)/2;
var calcY = (canvasSize.height - calcH)/2;
// Load input image into canvas
const img = document.createElement("img");
img.src = reader.result;
img.onload = () =>
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
//Load & draw the Stamp image
const mark = new Image();
mark.src = 'assets/img/compliant.png'; // <<TAINTED ASSET?
mark.onload = () =>
ctx.drawImage(mark, calcX,calcY,calcW,calcH);
// Convert to blob and get URL
canvas.toBlob((canvasBlob) =>
const newImg = document.createElement("img"),
url = URL.createObjectURL(canvasBlob);
newImg.onload = function ()
//Destroy objecturl after image loading
URL.revokeObjectURL(url);
;
// Show stamped image
newImg.src = url;
window.open(url);
);
;
;
;
);
【问题讨论】:
【参考方案1】:你必须使用 img.crossOrigin='匿名的'; 在您要操作的每个图像上(在画布中绘制,转换为数组缓冲区……这是为了防止您操作潜在的私人用户数据) https://developer.mozilla.org/en-US/docs/Web/html/Element/video#attr-crossorigin
【讨论】:
以上是关于无法在javascript中将图像绘制到画布的主要内容,如果未能解决你的问题,请参考以下文章