我有画布,其中一个图像显示为背景,其他图像放在该图像的中心。现在我想保存完整的画布。我最近的代码没有保存它..
您可以在此处查看演示[http://jsfiddle.net/himani/gqc9b0qd/3/]
var can = document.getElementsByTagName('canvas')[0];
var ctx = can.getContext('2d');
ctx.strokeStyle = '#f00';
ctx.lineWidth = 6;
ctx.lineJoin = 'round';
ctx.strokeRect(40,100,150,100);
var angleInDegrees=0;
var img = document.getElementsByTagName('img')[0];
img.src="http://media1.santabanta.com/full1/Miscellaneous/Cartoon%20Characters/cartoon-characters-47a.jpg";
ctx.drawImage(img,40,100,150,100);
function drawRotated(degrees){
ctx.clearRect(0,0,300,300);
ctx.save();
ctx.translate(40+150/2,100+100/2);
ctx.rotate(degrees*Math.PI/180);
ctx.strokeRect(-150/2,-100/2,150,100);
ctx.drawImage(img,-150/2,-100/2,150,100);
ctx.restore();
}
$("#clockwise").click(function(){
angleInDegrees+=30;
drawRotated(angleInDegrees);
});
$("#save").click(function(){
var ua = window.navigator.userAgent;
if (ua.indexOf("Chrome") > 0) {
// save image without file type
var canvas = document.getElementsByTagName('canvas')[0];
document.location.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
// save image as png
var link = document.createElement('a');
link.download = "test1.png";
link.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");;
link.click();
}
else {
alert("Please use Chrome");
}
});
答案 0 :(得分:0)
如果您想使用toDataUrl从跨源请求中导出图像,请尝试在图像上定义 crossOrigin 属性。
var img = document.getElementsByTagName('img')[0];
img.crossOrigin = "anonymous";
img.src="http://media1.santabanta.com/full1/Miscellaneous/Cartoon%20Characters/cartoon-characters-47a.jpg";
img.onload = function () {
ctx.drawImage(img,40,100,150,100);
};
它对我来说很好。有关此属性和可用值的更多信息,请查看https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Img#Attributes