本文介绍了本地主机上的 context.getImageData()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码片段,我正在尝试从本地主机(OSX,运行 XAMPP)运行它:

I have the following snippet of code and I'm trying to run it from localhost (OSX, running XAMPP):

var canvas = document.getElementById('mycanvas');
    var cx = canvas.getContext('2d');

    var myImg = new Image();
    myImg.src = 'images/lion.jpg';

    $(myImg).load(function() {
        cx.drawImage(myImg, 0, 0);
        var imgData = cx.getImageData(0,0,150,150);
    });

但是当我运行它时,我从控制台收到此错误:

But when I run it I get this error from the console:

Unable to get image data from canvas because the canvas has been tainted by cross-origin data.
site.js:11Uncaught Error: SECURITY_ERR: DOM Exception 18

我在这里发现了一些类似的问题,我知道这与我在本地工作的事实有关,如果我试图从同一域访问图像,则不会发生这种情况.我不知道这是否有意义,但这是我的理解.

I found some similar questions here and I know that this has something to do with the fact that I'm working locally and this wouldn't happen if I was trying to access the image from the same domain. I don't know if this makes sense, but it's what I understood.

我的问题是,如何在本地开发环境中进行这项工作?

My question is, how can I make this work in a local dev environment?

推荐答案

使用 HTTP 服务器(例如 Apache 或 Nginx)提供您的 html.

Serve your html with an HTTP server, for example, Apache or Nginx.

Mac OSX 安装了 Python,所以你可以简单地通过打开一个终端来启动一个 HTTP 服务器,然后输入:

Mac OSX comes with Python installed, so you can simply start an HTTP server by opening a terminal, then input:

cd /path/to/my/work/
python -m SimpleHTTPServer

然后在浏览器中打开 http://localhost:8000/.这应该有效.

Then open http://localhost:8000/ in your browser. This should work.

这篇关于本地主机上的 context.getImageData()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 03:46