我在用drawImage()。这是我的密码。imDiv持有一个内联svg。
var c =document.getElementById( 'cvs' );
var ctx =c.getContext( '2d' );
var img =document.getElementById( 'imDiv' );
ctx.drawImage( img, 0, 0 ); //TypeMismatchError我收到了一个TypeMismatchError错误。原因可能是什么,我如何解决这个问题?

发布于 2015-03-31 23:07:51
您必须首先将SVG转换为图像,然后将图像绘制到画布上。
有些事情你需要考虑:
foreignObject (嵌入HTML等)时,会有不同的安全限制,这取决于浏览器。它会在一些地方工作(火狐,没有外部引用),另一些则不起作用(f.ex )。(铬)这目前处于真空状态,在客户端我们对此无能为力。下面是这样做的一种方法:
// Inline SVG:
var svg = document.querySelector('svg').outerHTML, // make sure SVG tags are included
canvas = document.querySelector('canvas'), // target canvas
ctx = canvas.getContext('2d');
// convert to image (see function below)
// converting to image is an asynchronous process, so we need a callback
svgToImage(svg, function(img) {
// HERE you could insert the image to DOM:
// var myElement = document.getElementById(elementID);
// myElement.appendChild(img);
// set canvas size = image
canvas.width = img.width;
canvas.height = img.height;
// draw SVG-image to canvas
ctx.drawImage(img, 0, 0);
});
// this will convert an inline SVG to a DATA-URI
function svgToImage(svg, callback) {
var url = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg),
img = new Image;
// handle image loading, when done invoke callback
img.onload = function() {
callback(this);
};
img.src = url;
}<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
<linearGradient id="gradient">
<stop offset="0%" stop-color="#00f" />
<stop offset="100%" stop-color="#f70" />
</linearGradient>
<rect fill="url(#gradient)" x="0" y="0" width="100%" height="100%" />
</svg>
<br>
<canvas></canvas><br>
发布于 2015-03-31 17:26:00
到目前为止,不可能在画布上绘制div或svg元素。传递给context.drawImage()的第一个参数必须是Image、画布,甚至是视频元素(使用svg可能会导致TypeMismatchError)。
因此,您可以使用getElementById()检索文档上的实际getElementById(),或者用new Image()创建文档。
https://stackoverflow.com/questions/29369403
复制相似问题