使用 Chrome 在画布上本地绘制图像

Posted

技术标签:

【中文标题】使用 Chrome 在画布上本地绘制图像【英文标题】:Draw images on canvas locally using Chrome 【发布时间】:2013-02-11 14:10:13 【问题描述】:

我有一个必须在本地运行的 html5 应用程序。当我运行应用程序并尝试在画布上加载图像时,在 Chrome 上我收到错误消息:

无法从画布中获取图像数据,因为画布已经 被跨域数据污染

本地文件夹中的 HTML 文档和图像。 这是一个将分发给用户的应用程序,因此我无法运行本地服务器。它必须在 Chrome 上按原样运行... 我已阅读有关此问题的答案,但它们都与与本地文件无关的 CORS 和跨组织策略有关......

这种情况的解决方案是什么?如何在 Chrome 本地加载画布上的图像?

编辑: 这是引发错误的代码:

var canvas = Matach.createElement(false, "canvas", false, false);           
var context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.globalCompositeOperation = 'source-over';

context.save();
context.drawImage(
    item.img.img, 
    -item.img.width / 2, 
    -item.img.height / 2, 
    item.img.width, 
    item.img.height
);

context.restore();

res = context.getImageData(0, 0, canvas.width, canvas.height);

【问题讨论】:

你能发布一些代码吗? 添加了代码。它是更大应用程序的一部分。 跨源策略相关的。它可以确保本地图像数据在没有明确用户指示的情况下无法上传到远程站点。 但是这里没有上传到远程站点。它只是在本地机器的画布上绘制图像。怎样才能做到不出错? 【参考方案1】:

在 chrome 中 getimagedata 存在一些安全问题,所以使用这个你必须做一些周转,查看这些帖子以供参考,你会得到解决方案,

canvas getImageData doesn't work when running locally on Windows? (security exception)

Why does HTML Canvas getImageData() not return the exact same values that were just set?

【讨论】:

以上是关于使用 Chrome 在画布上本地绘制图像的主要内容,如果未能解决你的问题,请参考以下文章

无法在javascript中将图像绘制到画布

在 Chrome 上使用 drawImage 和 Canvas 非常慢

使用 Retina 显示屏在画布上绘制图像

在画布上的图像不透明部分周围绘制边框

如何将多个图像绘制到单个画布上?

ios在画布上使用display:none绘制图像导致内存泄漏