使用 JavaScript 将画布转换为图像 [英] Convert canvas to an image with JavaScript

查看:37
本文介绍了使用 JavaScript 将画布转换为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 JavaScript 将画布转换为图像,当我尝试 canvas.toDataURL("image/png"); 时出现以下错误

I want to convert canvas to an image with JavaScript, When I try to canvas.toDataURL("image/png"); It gives the following error

安全错误:操作不安全

推荐答案

你的想法是对的,它适用于非常简单的情况,例如:

You have the right idea, and it will work in very simple cases such as:

var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');

ctx.fillRect(50,50,50,50);

var img = new Image();
img.src = can.toDataURL();
document.body.appendChild(img);

http://jsfiddle.net/simonsarris/vgmFN/

但是如果您弄脏"了画布,就会出现问题.这是通过将来自不同来源的图像绘制到画布上来完成的.例如,如果您的画布托管在 www.example.com,并且您使用来自 www.wikipedia.org 的图像,那么您的画布的 origin-clean 标志会在内部设置为 false.

But it becomes problematic if you have "dirtied" your canvas. This is done by drawing images to the canvas that are from a different origin. For instance, if your canvas is hosted at www.example.com, and you use images from www.wikipedia.org, then your canvas' origin-clean flag is set to false internally.

一旦 origin-clean 标志设置为 false,您就不能再调用 toDataURLgetImageData

Once the origin-clean flag is set to false, you are no longer allowed to call toDataURL or getImageData

从技术上讲,如果域、协议和端口匹配,则图像具有相同的来源.

Technically, images are of the same origin if domains, protocols, and ports match.

如果您在本地工作 (file://),那么绘制的任何图像都会触发标志.这让调试变得烦人,但是在 Chrome 中,您可以使用标志 --allow-file-access-from-files 启动它以允许这样做.

If you are working locally (file://) then any image drawn will set off the flag. This makes debugging annoying, but with Chrome you can start it with the flag --allow-file-access-from-files to allow this.

这篇关于使用 JavaScript 将画布转换为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆