简体   繁体   English

为什么在Canvas(JS)中,在drawImage()之后toDataUrl()不起作用?

[英]Why in Canvas(JS) toDataUrl() doesn't work after drawImage()?

<script>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');
  var img = new Image();
  img.onload = function(){
    canvas.width=img.width;
    canvas.height=img.height;
    context.drawImage(img,0,0);
  }
  img.src="2.jpg";
  function compress(){
    var dataURL = canvas.toDataURL("image/jpg",0.5);
    document.getElementById("img").src=dataURL;
  }          
  setTimeout(compress,1000);
</script>

I've tried to use as example fillRect() instead of drawImage() . 我尝试使用fillRect()代替drawImage()作为示例。 So it works normally... I'm sure that reason is drawImage() 所以它可以正常工作...我确定原因是drawImage()

If your image URL (the original URL, not the data URL) is from a different domain than that of the page where the code runs, then the canvas will be tainted when you draw the image to it, and you wont be able to get the pixels back out. 如果您的图片网址(原始网址,而不是数据网址)来自与代码运行页面所在的域不同的域,则在将图片绘制到画布上时,画布将被污染 ,并且您将无法获取像素退回。 That's a security measure. 这是一种安全措施。 Thus if you're testing on jsfiddle and you're using http://placekitten.com/100/100 urls to test, it won't work. 因此,如果您正在jsfiddle上进行测试,并且正在使用http://placekitten.com/100/100网址进行测试,则它将无法正常工作。

Note that most modern browsers do not consider two file:// URLs to share a domain, so if you're running the test from local files, it won't work. 请注意,大多数现代浏览器都不考虑两个file:// URL共享一个域,因此,如果您从本地文件运行测试,它将无法正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM